Mongo with mongoose

How to create Modal for CURD using Mongoose in express-node app


Mongoose is MongoDB driver module which provide REST features to build faster MongoDB apps with Nodejs.

Modal

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
         })

That’s it. Following mongoose posts deserve your attention

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.