Connecting to MongoDB using Mongoose

Posted by: Ravi Kiran , on 8/16/2015, in Category Node.js
Views: 19594
Abstract: Mongoose creates an abstraction on top of MongoDB driver to interact with the MongoDB database. In this article we will see how to use Mongoose to work with MongoDB.

In the previous article, we saw how Node.js interacts with MongoDB using the MongoDB driver. The MongoDB driver provides a similar interface that is used on the command line. There are other drivers that provide abstractions on the MongoDB driver and provide a different and a higher level API to interact with MongoDB. Mongoose is one of them and it is the most widely used MongoDB driver.

Like any other NoSQL databases, MongoDB is schema less. But Mongoose works on schemas. So mongoose is similar to any ORM used with SQL databases. Let’s see how we can use Mongoose to work with MongoDB.

Note: If you are new to Node.js, please go through these articles to gain a good understanding of Node.

Node.js Tutorial Series - Getting Started

Node.js Serving HTML pages and Static content

Using Node.js to build REST APIs

Node.js Module System

Understanding NPM

Installing and Referring Mongoose

Mongoose can be installed into a Node.js application using NPM.

> npm install mongoose --save

We can get the reference of the mongoose object by loading the module using the require function.

var mongoose=require('mongoose');

Like other Node.js APIs performing network and I/O operations, the APIs of Mongoose are asynchronous as well.

Connecting and Creating Schema

The connection to MongoDB can be established from Mongoose using the connect function of mongoose object created above. Instance of the connected database is stored in the connection property of the mongoose object.

mongoose.connect("mongodb://localhost/testDb");
var db=mongoose.connection;

The above snippet may connect to the database or, it may result in an error for some reason. The db object in the above snippet emits events on error or, upon successfully connecting to the database. Following snippet listens to these events:

db.on('error', console.error.bind(console, "connection error"));
db.once('open', function () {
  console.log("Connection to testDb is open...");
});

The mongoose.connect function connects to the database if it exists. Otherwise, it creates the database and then connects to it.

Schema for a collection can be created using the mongoose object. We need to create a model object using the schema. The model object will be used to perform CRUD operations on the collection.

var todoSchema = mongoose.Schema({
   id: Number,
   title: String,
   done: Boolean
});
todoModel = mongoose.model('todo', todoSchema);

The first parameter to the model function is name of the model. Name of the collection will be a pluralized name of the model’s name. So here name of the collection will be todos.

Performing CRUD Operations

As already mentioned, the model object is going to be our agent to operate with the collection. Using this object, let’s seed some data into the collection if the collection doesn’t have any data yet. We need to perform two operations for this task: one is to find if there are any documents and then create documents if the count is zero. Following snippet does this task:

todoModel.find().exec(function (error, results) {
  if (results.length === 0) {
    todoModel.create({ id:1, title:"Prepare tea", done:false });
    todoModel.create({ id:2, title:"Brush teeth", done:false });
    todoModel.create({ id:3, title:"Toast Bread", done:false });
    todoModel.create({ id:4, title:"Have breakfast and tea", done:false });
  }
});

The find function on the model object returns all documents in the collection. We can filter the documents based on a condition. The condition has to be passed into the find() function as an object. Following snippet fetches the unfinished todo items:

todoModel.find({done: false}).exec(function (error, result) {
   console.log(result);
});

The create() method on the model object adds a new document to the collection. The document passed to this function should match the schema added to the model object. If it has any properties that are not configured in the schema, they will be discarded while inserting data into the collection.

Existing documents can be modified using model.update() method. This method accepts a condition to filter the documents to be modified, an object containing the changes to be applied and an object containing whether to update multiple documents. Like find and create, it accepts a callback function that will be called once the operation is completed.

todoModel.update({id: 2}, {title:"Take bath", done: true}, {multi: false}, function (error, result) {
   if(error) {
      //Handle error
   }
   else{
      //Use result
   }
});

Similarly, the remove() function is used to remove an object from the collection. Following is an example:

todoModel.remove({id: 4}, function (error, result) {
  if(error) {
    console.log(error);
  }
  else{
    console.log(result);
  }
});

Conclusion

Mongoose creates an abstraction on top of  MongoDB driver to interact with the MongoDB database. Though usage of schema sounds a bit weird while interacting with a schema-less database, using schema has its own advantages. We will use Mongoose in more examples in future.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Rabi Kiran (a.k.a. Ravi Kiran) is a developer working on Microsoft Technologies at Hyderabad. These days, he is spending his time on JavaScript frameworks like AngularJS, latest updates to JavaScript in ES6 and ES7, Web Components, Node.js and also on several Microsoft technologies including ASP.NET 5, SignalR and C#. He is an active blogger, an author at SitePoint and at DotNetCurry. He is rewarded with Microsoft MVP (Visual Studio and Dev Tools) and DZone MVB awards for his contribution to the community


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook