Mongoose CURD

How to create Mongoose models for CURD

Sat Jun 19 2021

Mongoose allow us to perform CURD operation using REST full Modals. A Modal is basically is an object/class which define all fields with validation and also connected to your MongoDB.

To perform operation ,create variables of the modal and call the save/ create method. Following is a sample Modal class

const mongoose = require('mongoose');
 const UserSchema = new mongoose.Schema({
     name :{
         type:String,
         required: '{PATH} is required!'
     },
     bio: {
         type:String
     },
     email:{
         type:String
     },
     website:{
         type:String
     },
     password:{type:String,required: '{PATH} is required!',default:"123"},
 `posts : [     {type: mongoose.Schema.Types.ObjectId,ref:'Post'} ]`
 },{
     timestamps: true
 })
 module.exports = mongoose.model('User',UserSchema);

In the modal class you can store another document using **_ObjectID_** .Here is an example for the _**create**_ document using the modal class

const user = await User.create({
             name,
             email,
             bio,
             website
         })

Comments