Steps involved in creating models in express js
- First we need to import mongooose
- To make it modular, Lets create a new folder named models and then create a new js file . In this example I am creating model named user. It has 2 properties firstName and lastName.
- Load the model into mongoose
var mongoose =require('mongoose') //Model for fetching users var userSchema=mongoose.Schema({ firstName:{ type:String, required:true }, lastName:{ type:String } }); //User Model module.exports=mongoose.model('User',userSchema)
- Import the model and then we can load it as needed.
//Load the model for users User=require('./models/user'); //Using find to fetch all the users in the db app.get("/api/Users",function(req,res){ User.find({},function (err,user){ if(err) { console.log(err); res.send(err); } else { console.log(user); res.send(user);} }); });
No comments:
Post a Comment