There are two ways to interact with Mongo DB database in Node JS, use MongoDB drivers or use Mongoose which is (MongoDB ODM).

Mongoose ODM

Mongoose is MongoDB's Object Document Mapper ( ODM ) designed to work in an asynchronous environment. 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.

In SQL based databases, we use ORM, but in NoSQL based databases like MongoDB, we use ODM.


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

Configure Mongoose in Node JS

Promise based for Mongoose 6 and above

            /*dao.js*/
    // getting-started.js
    const mongoose = require('mongoose');
    
    main().catch(err => console.log(err));
    
    async function main() {
      await mongoose.connect('mongodb://127.0.0.1:27017/node');
    
      // use `await mongoose.connect('mongodb://user:password@127.0.0.1:27017/test');` if auth enabled
    
      console.log("Db Connected");
    }
   

Callback based for Mongoose 5 and below

            /*dao.js*/
 const mongoose=require('mongoose');
 
 mongoose.connect('mongodb://127.0.0.1:27017/node').then(() => console.log('Connected to database!'));

 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

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.

Supported Schema Types

  1. String
  2. Number
  3. Date
  4. Buffer
  5. Boolean
  6. ObjectId
  7. Array
  8. Decimal128
  9. Map
 
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Car = new Schema({
    _id:mongoose.ObjectId,
    name:String,
    type:String,
    price:Number
},{collection:"collectionName"});

Schema with validation

We can also validate schemas in mongoose.

 
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
  
const Car = new Schema({
  _id:mongoose.ObjectId,
  name:{type:String, required:true, unique: true, dropDups:true},
  type:{type:String, required:true},
  price:{type:Number, required:true, min:0, max:1000000}
},{collection:"collectionName"});

Create a model

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

Another object with key collection is used to specify name of collection used. If collection is not available, mongoose will pluralizes the name of model.


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

const Car = new Schema({
    _id:mongoose.ObjectId,
    name:{ type: String, required: true, unique: true, dropDups: true },
    type:{ type: String, required: true },
    price:{ type: Number, required: true },
    date: { type: Date, default: Date.now },
},{collection:"cars"}); 

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

Create instance of model

Now we have to create an instance of model to add data in database.


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

const Car = new Schema({
    _id:mongoose.ObjectId,
    name:{ type: String, required: true },
    type:{ type: String, required: true },
    price:{ type: Number, required: true },
    date: { type: Date, default: Date.now },
},{collection:"cars"}); 

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

let car=new model({name:'swift',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({
    _id:mongoose.ObjectId,
    name:{ type: String, required: true },
    type:{ type: String, required: true },
    price:{ type: Number, required: true },
    date: { type: Date, default: Date.now },
},{collection:'suzuki'});


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

let carname=new car({
  _id:new mongoose.Types.ObjectId(),
  name:"swift",
  type:"hatchback",
  price:800000
});

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

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

   carname.save()
   .then(i=>res.status(200).send("data saved"))
   .catch(i=>res.status(200).send("data not saved"));
   
});     

Run Code

swift saved to collection.

node src/dao

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({
    _id:mongoose.ObjectId,
    name:String,
    type:String,
    price:Number,
  },{collection:'cardata'});

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


  car.find({name:"swift"})
  .then(i=>console.log(i))
  .catch(err=>console.warn(err));


  /*
  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

Find particular fields only

We can also find method to fetch only particular fields, like car name and brand only from db, not all data. See example below


car.find({type:"hatchback"})
.then(i=>console.log(i))
.catch(i=>console.log(i))

Run Code


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

Limit queries

We can also limit our output to specific number of items using limit(). See example below


car.find({type:"hatchback"}).limit(2).then(i=>console.log(i));

Run Code


mongoose connected!
[
  {
    _id: 5eb81a2fbe672314a543269e,
    name: 'swift',
    type: 'hatchback'
  },
  {
    _id: 5eb5378791fc73f290f38252,
    name: 'baleno',
    type: 'hatchback'
  }
]
node src/dao

Sort

We can use sort() function to sort output by passing 1 value for accending order. For descending sort, use -1. See example below


car.find({}).sort({name:1}).then(i=>console.log(i));

Run Code


mongoose connected!
[
  {
    _id: 5eb5378791fc73f290f38252,
    name: 'baleno',
    type: 'hatchback'
  },
  {
    _id: 5eb81a2fbe672314a543269e,
    name: 'swift',
    type: 'hatchback'
  }
]
node src/dao