Mongoose | Node JS with Mongoose | Mongoose in Express

Mongoose

Written By: Avinash Malhotra

Updated on 23-Apr-2022

  • MongoDB NodeJS

  • Passport JS

Node JS

Tutorial

rating

Average rating:

5.0

, based on

189

reviews

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

            /*dao.js*/
 const mongoose=require('mongoose');
 mongoose.connect('mongodb://localhost:27017/database', {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

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

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.

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:"cardata"}); 

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

var carname=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'});


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

var 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('mongoose connected!');

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

Run Code

mongoose connected!

dzire 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'});

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

Find only particular fields

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"},'name type',(err,data)=>{
    if(err){console.log(err)}
    else{ console.log(data)}
});

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"},(err,data)=>{
    if(err){console.log(err)}
    else{ console.log(data)}
}).limit(3);

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({},(err,data)=>{
    if(err){console.log(err)}
    else{ console.log(data)}
}).sort({name:1});

Run Code


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

node src/dao