36
loading...
This website collects cookies to deliver better user experience
import { Schema, model } from 'mongoose';
// 1. Create an interface representing a document in MongoDB.
interface User {
name: string;
email: string;
avatar?: string;
}
// 2. Create a Schema corresponding to the document interface.
const schema = new Schema<User>({
name: { type: String, required: true },
email: { type: String, required: true },
avatar: String
});
// 3. Create a Model.
const UserModel = model<User>('User', schema);
User
schema twice: once with typescript types and once with mongoose types. The added verbosity only grows as the complexity of your schema does, and soon enough it's a living nightmare 💀.tsconfig.json
:{
"compilerOptions": {
// ...
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
mongoose
and @typegoose/typegoose
with the package manager of your choice.import { getModelForClass, prop } from '@typegoose/typegoose';
class User {
@prop()
name!: string;
@prop()
email!: string;
@prop()
avatar?: string;
}
const UserModel = getModelForClass(User);
prop
decorator), typegoose will automatically infer the type of each property using reflect-metadata. Super cool, right? (Note that this gets a bit fuzzy around arrays).