- Published on
How to setup NextJS with Mongoose and TypeScript
- Authors
- Name
- John Mwendwa
- Github
- John
To get started with Mongoose and TypeScript, you need to:
- Create an interface representing a document in MongoDB.
- Create a Schema corresponding to the document interface.
- Create a Model.
- Export the model
1import { Model, Types, Schema, model, models } from "mongoose"; 2 3export interface UserProps { 4 _id: Types.ObjectId; 5 firstName: string; 6 lastName: string; 7 email: string; 8 password: string; 9 avatar: Buffer; 10 createdAt: Date; 11 updatedAt: Date; 12} 13 14const userSchema = new Schema<UserProps>( 15 { 16 firstName: { 17 type: String, 18 required: [true, "First name is required"], 19 }, 20 lastName: { 21 type: String, 22 required: [true, "Last name is required"], 23 }, 24 email: { 25 type: String, 26 required: [true, "Email is required"], 27 unique: true, 28 lowercase: true, 29 }, 30 31 password: { 32 type: String, 33 required: [true, "Password is required"], 34 }, 35 36 avatar: { 37 type: Buffer, 38 }, 39 }, 40 { timestamps: true } 41); 42 43 44const User = 45 (models.User as Model<UserProps>) || 46 model<UserProps>("User", userSchema); 47 48export default User; 49
Creating refs using ObjectIds
When you want to reference a mongoose model inside another model, you should use Types.ObjectId
in the TypeScript document interface and ObjectId
or Schema.Types.ObjectId
inside your schema definition according to the mongoose documentation.
1import { Schema, Types } from 'mongoose'; 2 3 // Use **Types.ObjectId** in document interface. 4interface PostProps { 5... 6authorID:Types.ObjectId 7} 8 9// And **Schema.Types.ObjectId** in the schema definition. 10const postSchema = new Schema<PostProps>({ 11... 12authorID:{ 13type : Schema.Types.ObjectId, 14ref:"User" 15})