Connect Nodejs, Express to MongodB using Mongoose
Mongoose is an Object Data Modelling (ODM) Library for MongoDB and NodeJS. it manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.
How to connect MongoDB to NodeJS using Mongoose ?
first of all, install mongoos in npm package using "npm install mongoose" command then
mongoose provides connect property for connecting mongoDB.
mongoose.connect(URL, useNewUrlParse)
useNewUrlParse : -The underlying MongoDB driver has deprecated their current connection string parser.
the we use promises because it handle error. If an error occurs.
const mongoose = require('mongoose');// connection creationmongoose.connect("mongodb://localhost:27017/test",{useNewUrlParser: true})// use promises.then(()=>{console.log("connction successful...")}).catch((err)=>console.log(err));
connction successful...What is Schema and Model in Mongoose?
Schema :- A Mongoose schema defines the structure of the document, default values, validators, etc...
Model :- A Mongoose model is a wrapper on the Mongoose schema.const playlistSchema = new mongoose.Schema ({// define schemaname:{type : String,required : true},sirname : String,email : String,role : String,active : Boolean,date : {type: Date,default : Date.now}})
A Mongoose schema defines the structure of the document, default values, validators, etc., where as a Mongoose model provides an interface to the database for creation, querying, updating, deleting records, etc.
// collection creation// in model("collection name", define schema)const PlayList = new mongoose.model("PlayList",playlistSchema)
Post a Comment