Mongoose the Typescript way...? Mongoose the Typescript way...? mongoose mongoose

Mongoose the Typescript way...?


Here's how I do it:

export interface IUser extends mongoose.Document {  name: string;   somethingElse?: number; };export const UserSchema = new mongoose.Schema({  name: {type:String, required: true},  somethingElse: Number,});const User = mongoose.model<IUser>('User', UserSchema);export default User;


Another alternative if you want to detach your type definitions and the database implementation.

import {IUser} from './user.ts';import * as mongoose from 'mongoose';type UserType = IUser & mongoose.Document;const User = mongoose.model<UserType>('User', new mongoose.Schema({    userName  : String,    password  : String,    /* etc */}));

Inspiration from here: https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models


Sorry for necroposting but this can be still interesting for someone.I think Typegoose provides more modern and elegant way to define models

Here is an example from the docs:

import { prop, Typegoose, ModelType, InstanceType } from 'typegoose';import * as mongoose from 'mongoose';mongoose.connect('mongodb://localhost:27017/test');class User extends Typegoose {    @prop()    name?: string;}const UserModel = new User().getModelForClass(User);// UserModel is a regular Mongoose Model with correct types(async () => {    const u = new UserModel({ name: 'JohnDoe' });    await u.save();    const user = await UserModel.findOne();    // prints { _id: 59218f686409d670a97e53e0, name: 'JohnDoe', __v: 0 }    console.log(user);})();

For an existing connection scenario, you can use as the following (which may be more likely in the real situations and uncovered in the docs):

import { prop, Typegoose, ModelType, InstanceType } from 'typegoose';import * as mongoose from 'mongoose';const conn = mongoose.createConnection('mongodb://localhost:27017/test');class User extends Typegoose {    @prop()    name?: string;}// Notice that the collection name will be 'users':const UserModel = new User().getModelForClass(User, {existingConnection: conn});// UserModel is a regular Mongoose Model with correct types(async () => {    const u = new UserModel({ name: 'JohnDoe' });    await u.save();    const user = await UserModel.findOne();    // prints { _id: 59218f686409d670a97e53e0, name: 'JohnDoe', __v: 0 }    console.log(user);})();