Trying to implement a Mongoose model in Typescript. Scouring the Google has revealed only a hybrid approach (combining JS and TS). How would one go about implementing the
Here's a strong typed way to match a plain model with a mongoose schema. The compiler will ensure the definitions passed to mongoose.Schema matches the interface. Once you have the schema, you can use
common.ts
export type IsRequired =
undefined extends T
? false
: true;
export type FieldType =
T extends number ? typeof Number :
T extends string ? typeof String :
Object;
export type Field = {
type: FieldType,
required: IsRequired,
enum?: Array
};
export type ModelDefinition = {
[P in keyof M]-?:
M[P] extends Array ? Array> :
Field
};
user.ts
import * as mongoose from 'mongoose';
import { ModelDefinition } from "./common";
interface User {
userName : string,
password : string,
firstName : string,
lastName : string,
email : string,
activated : boolean,
roles : Array
}
// The typings above expect the more verbose type definitions,
// but this has the benefit of being able to match required
// and optional fields with the corresponding definition.
// TBD: There may be a way to support both types.
const definition: ModelDefinition = {
userName : { type: String, required: true },
password : { type: String, required: true },
firstName : { type: String, required: true },
lastName : { type: String, required: true },
email : { type: String, required: true },
activated : { type: Boolean, required: true },
roles : [ { type: String, required: true } ]
};
const schema = new mongoose.Schema(
definition
);
Once you have your schema, you can use methods mentioned in other answers such as
const userModel = mongoose.model('User', schema);