How to use Node.js Mongoose with TypeScript?

Sometimes, we want to use Node.js Mongoose with TypeScript.

In this article, we’ll look at how to use Node.js Mongoose with TypeScript.

How to use Node.js Mongoose with TypeScript?

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.