Develop Node.js Application with MongoDB and Mongoose

August 21, 2017

In this lesson, I am going to explain how you can build the Node.js app using the MongoDB and NPM package Mongoose
First, be sure you have MongoDB and Node.js installed

What is Mongoose?
It is an object modelling package. It is same as ORM (Object Relation Mapping) what you find in other languages for Relational Databases access
With Mongoose you can do CRUD operations and easily

First thing you have to do is, installing the Mongoose
In your terminal

$ npm install mongoose --save

After installing the Mongoose package, you can connect to the database using the following two lines in your index.js file

var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test',{useMongoClient: true})

So now, we have connected to database
Lets create a model for our collection

Defining a Model

Before creating the model, I am going to create a Schema using mongoose.Schema. This model maps with the document in collection

This is the Schema for the product. This Schema just defines the attributes in your document

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test',{useMongoClient: true});
var Schema = mongoose.Schema;

var productSchema = new Schema({
   product_id:{type:String,required:true,unique:true},
   product_name:{type:String,required:true},
   unit_price:Number

})

The permitted SchemaTypes are

var Product = mongoose.model('Product', productSchema);

String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array

When your schema is ready you can create your model now

var Product = mongoose.model('Product', productSchema);

Create Document

Now lets see how we create new product and save it

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test',{useMongoClient: true});
var Schema = mongoose.Schema;

var productSchema = new Schema({
	product_id:{type:String,required:true,unique:true},
	product_name:{type:String,required:true},
	unit_price:Number

})

var Product = mongoose.model('Product', productSchema);

var prdocut= new Product({
	product_id:1,
	product_name:'Coca Cola',
	unit_price:1.25
})

prdocut.save(function(err) {
  if (err) throw err;

  console.log('Product saved successfully!');
});

Code explanation

  • Line 14: New product is created using the model we created
  • Line 25: Save the product using but-in save() of the Mongoose

Read Document

You can get all products, only one product, product by id and you can specify the query to get set of products. We will see how we are going to achieve it

Find all products

Product.find({}, function(err, products) {
  if (err) throw err;

  console.log(products);
});

You will get following output in terminal

[ { _id: 599ac9c41f6e75af47e8140b,
    product_id: '1',
    product_name: 'Coca Cola',
    unit_price: 1.25,
    __v: 0 },
  { _id: 599ad83c9cd889afaf5fc800,
    product_id: '2',
    product_name: 'Fanta',
    unit_price: 1.35,
    __v: 0 },
  { _id: 599ad86506f67fafb26d74b8,
    product_id: '3',
    product_name: 'Sprite',
    unit_price: 1.45,
    __v: 0 } ]

Find one product
To find one product, you have to specify the product attribute so that Mongoose can locate it

var product={product_name:'Coca Cola'}
Product.find(product, function(err, product) {
  if (err) throw err;

  console.log(product);
});

Terminal Output

[ { _id: 599ac9c41f6e75af47e8140b,
    product_id: '1',
    product_name: 'Coca Cola',
    unit_price: 1.25,
    __v: 0 } ]

Find product by Id

Product.findById('599ad83c9cd889afaf5fc800', function(err, product) {
  if (err) throw err;

  console.log(product);
});

Find product by querying
You can find product by making query. MongoDB has good query syntax. You can refer it for more details
In this example I am going to find products which unit prices are greater than 1.25

Product.find({}).where('unit_price').gt(1.25).exec(function(err, products) {
  if (err) throw err;

  console.log(products);
});

Terminal Output

[ { _id: 599ad83c9cd889afaf5fc800,
    product_id: '2',
    product_name: 'Fanta',
    unit_price: 1.35,
    __v: 0 },
  { _id: 599ad86506f67fafb26d74b8,
    product_id: '3',
    product_name: 'Sprite',
    unit_price: 1.45,
    __v: 0 } ]

Update Document

There are several ways to do update document with Mongoose
First you can get the object and then update the attributes and finally save it. You can use findById() or findOne() to get the product object.
Other method is using the findOneAndUpdate()
Third one is findByIdAndUpdate()
We will how these methods one by one

Find the product first, then update

var product={product_name:'Coca Cola'}
Product.findOne(product, function(err, product) {
  if (err) throw err;
  product.unit_price=2
  product.save()
  console.log(product);
});

You can use findById() to get the product

Product.findById('599ac9c41f6e75af47e8140b', function(err, product) {
  if (err) throw err;
  product.unit_price=2
  product.save()
  console.log(product);
});

Using findOneAndUpdate()

var query={product_name:'Coca Cola'}
var updated={unit_price:2.00}
Product.findOneAndUpdate(query,updated, function(err, product) {
  if (err) throw err;
 
  console.log("Update Done");
});

Using findByIdAndUpdate()

var updated={unit_price:2.00}
Product.findByIdAndUpdate('599ac9c41f6e75af47e8140b',updated, function(err, product) {
  if (err) throw err;
 
  console.log("Update Done");
});

Those are the several method of updating the document. You can use the correct one according your requirements

Delete Document

To delete the document first you have to find it. There are several methods to delete document. It is same like what you learned in update document

Find the product first, then delete

var product={product_name:'Coca Cola'}
Product.findOne(product, function(err, product) {
  if (err) throw err;
  product.delete()
  console.log(product);
});

Using findOneAndRemove()

var product={product_name:'Coca Cola'}
Product.findOneAndRemove(product, function(err) {
  if (err) throw err;

  console.log("Product dleted");
});

Using findByIdAndRemove()

Product.findByIdAndRemove('599ac9c41f6e75af47e8140b', function(err) {
  if (err) throw err;
  console.log('Product deleted');
});

I hope that you have good understanding to work with Mongoose and Node.js to build your application now