Categories
JavaScript Answers

How to use Mongoose with TypeScript?

Spread the love

To use Mongoose with TypeScript, we define interfaces for our schemas.

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 define the IUser interface that inherits from the mongoose.Document interface.

Then we create the UserSchema with mongoose.Schema with a few fields in the object we call it with.

Next, we call model to map the 'User‘ table to UserSchema.

We set the type of the fields to match the IUser with the generic type argument.

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 *