Categories
TypeScript Answers

How to use Node.js Mongoose with TypeScript?

Spread the love

To use Node.js Mongoose with TypeScript, we can create interfaces that extends interfaces provided by Mongoose.

For instance, we write

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;

to create the IUser interface that extends the mongoose.Document interface.

And then we use it to create our model with mongoose.model<IUser>.

Therefore, the User has the name and the optional somethingElse properties.

Conclusion

To use Node.js Mongoose with TypeScript, we can create interfaces that extends interfaces provided by Mongoose.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *