Mongoose

Mongoose is MongoDB Object Document Mapper i.e. ODM. MongoDB store data in JSON documents. Using Mongoose, we can map simple documents in full JS Objects with data, validations, schemas and business logics.

Mongoose provides schema based solution, typecasting, validation, query building, business logics and many more out of box features.


Install Mongoose

Mongoose is available on npm as mongoose. Install mongoose and include mongoose module in main app.

npm i mongoose

Mongoose is installed with MongoDB in NodeJS.


Configure

            /*dao.js*/
 const mongoose=require('mongoose');
 mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});

 const db=mongoose.connection;
 db.on('error', function (err) { throw err }); 
 db.once('open', function callback() {
    console.log('connected!');
db.close();
});
    

Run Mongoose

connected

node src/dao.js

Schema

Mongoose Schema defines the field of document and their type for validation. Schema class can have n no of instance with argument object containing Schema in key-value pair. See example.

 
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Car = new Schema({
    name:String,
    type:String,
    price:Number
});

Supported Schema Types

  1. String
  2. Number
  3. Date
  4. Buffer
  5. Boolean
  6. ObjectId
  7. Array
  8. Decimal128
  9. Map

Create a model

Next step is to create a model from schemas using mongoose.model(). This is how we compile a model from schema.


const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Car = new Schema({
    name:String,
    type:String,
    price:Number
}); 

var model=mongoose.model("model",Car); 

Create instance of model

Now we have to create an instance of model


const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Car = new Schema({
    name:String,
    type:String,
    price:Number
}); 

var model=mongoose.model("model",Car); 

var dezire=new model({name:'dezire',type:'hatchback',price:800000});

Insert into Collection

Now finally we can use model.save() method to save data in database collection. Our database name is cars and collection name is suzuki. See example

    /*dao.js*/
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost:27017/cars', {useNewUrlParser: true, useUnifiedTopology: true});

const db=mongoose.connection;

const Schema=mongoose.Schema;

   const Car=new Schema({
    name:String,
    type:String,
    price:Number,
},{collection:'suzuki'});

var car=mongoose.model("car",Car);

var dezire=new car({name:"dezire",type:"hatchback",price:700000});

db.on('error', function (err) { throw err }); 

db.once('open', function() {
   console.log('mongoose connected!');

    dezire.save(function (err, data) {
     if (err){
         return console.log(err); db.close();
        }
     else{
         console.log(data.name + " saved to collection."); db.close();
        }
   });
   
});     

Run Code

mongoose connected!

dezire saved to collection.

node src/dao.js

Find in Collection

In this example, we will find a query in database. The database name is cars and collection name is suzuki saved in MongoDB.

    /*dao.js*/
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost:27017/cars', {useNewUrlParser: true, useUnifiedTopology: true});

const db=mongoose.connection;


db.on('error', function (err) { throw err }); 

db.once('open', function() {
   console.log('mongoose connected!');

   const Schema=mongoose.Schema;

   const Car=new Schema({
    name:String,
    type:String,
    price:Number,
},{collection:'suzuki'});

var car=mongoose.model("car",Car);

car.find({name:"swift"},(err,data)=>{
    if(err){console.log(err)}
    else{ console.log(data)}
});
   
});

Run Code


mongoose connected!
[
  {
    _id: 5eb81a2fbe672314a543269e,
    name: 'swift',
    type: 'hatchback',
    price: 800000
  }
]
node src/dao.js