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 “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: Date.now },
    last_modified_at: { type: Date, default: Date.now },
    is_active: { type: Boolean, default: true }
 },
   { collection: 'users'}
 );

The explanation of the above code is given below.

mongoose schema explanation

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

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

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

app.get('/_createUser', function(req, res) {
  // create the user
  var newUser = new User();
  newUser.username = "sample"
  newUser.password = "sample123";
  newUser.email = "sample@gmail.com";
  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
  newUser.save(function(err) {
    if (err) {
       console.log('Error in Saving user: ' + err);
       res.status(500);
       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" : "sample@gmail.com",
"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 about another node module. Till then, Stay Tune to learn Node.JS.

Advertisements

I am Siva Prasad Rao Janapati. Working as a software developer. 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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

DZone

DZone MVB

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