Mongoose : MongoDB Object Modeling for Node.JS

node mongoose mongodb

                In this article, we will see how to use “mongoose” to connect to “MongoDB” from Node.JS. Mongoose provides object modeling and schema for application data. Follow the below steps to work with mongoose.

Step 1: Install the “mongoose” node module dependency.

 npm install mongoose --save 

Step 2: Get the connection to the MongoDB.

var mongoose = require('mongoose');
var sampleMongoConnection = mongoose.createConnection('mongodb://localhost/sample_db', function(err) {
      if (err) {
           console.log("The connection to the MONGODB is failed");
      } else {
           console.log("The connection to the MONGODB is successful !!!");

Step 3: Define the mongo schema. The schema reflects the document structure in the MongoDB.

//create User schema
var userSchema = new mongoose.Schema({
    username: {type:String, required: true, trim: true},
    password: {type:String, required: true, trim: true},
    email: {type: String, required: true, trim: true},
    first_name: {type:String, required: true, trim: true},
    last_name: {type: String, required: true, trim: true},
    gender: {type: String, required: true, trim: true},
    date_of_birth: { type: Date, required: true },
    created_at: { type: Date, default: },
    last_modified_at: { type: Date, default: },
    is_active: { type: Boolean, default: true }
   { collection: 'users'}

The explanation of the above code is given below.

mongoose schema explanation

Step 4: Create a model from the userSchema created in the above step.

 var User = sampleMongoConnection.model('user', userSchema);

Step 6: Now, write the code to save user data into the “users” collection.

app.get('/_createUser', function(req, res) {
  // create the user
  var newUser = new User();
  newUser.username = "sample"
  newUser.password = "sample123"; = "";
  newUser.first_name = "sample first name";
  newUser.last_name = "sample last name";
  newUser.gender = "male";
  newUser.date_of_birth = new Date("11/08/1984");
  // save the user {
    if (err) {
       console.log('Error in Saving user: ' + err);
       res.send("user creation is not successful");

    } else {
      console.log('User Registration succesful');
      res.send("user creation is successful");

The explanation of the above code is given below.

mongoose save functionality

If you go to the sample_db and query the “users” collection, you are able to see the user document which we inserted in the above step.

"_id" : ObjectId("56234935f7564a742092814e"),
"date_of_birth" : ISODate("1984-11-07T18:30:00Z"),
"gender" : "male",
"last_name" : "sample last name",
"first_name" : "sample first name",
"email" : "",
"password" : "sample123",
"username" : "sample",
"is_active" : true,
"last_modified_at" : ISODate("2015-10-18T07:24:37.032Z"),
"created_at" : ISODate("2015-10-18T07:24:37.027Z"),
"__v" : 0

In the coming article, we will discuss another node module. Till then, Stay Tune to learn Node.JS.

I am Siva Prasad Rao Janapati. Working as Technical Architect. Has hands on experience on ATG Commerce(DAS/DPS/DCS), Mozu commerce, Broadleaf Commerce, Java, JEE, Spring, Play, JPA, Hibernate, Velocity, JMS, Jboss, Weblogic,Tomcat, Jetty, Apache, Apache Solr, Spring Batch, JQuery, NodeJS, SOAP, REST, MySQL, Oracle, Mongo DB, Memcached, HazelCast, Git, SVN, CVS, Ant, Maven, Gradle, Amazon Web services, Rackspace, Quartz, JMeter, Junit, Open NLP, Facebook Graph,Twitter4J, YouTube Gdata, Bazzarvoice,Yotpo, 4-Tell, Alatest, Shopzilla, Linkshare. I have hands on experience on open sources and commercial technologies.

Tagged with:
Posted in Node.js

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.



Java Code Geeks
Java Code Geeks
%d bloggers like this: