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.


Siva Janapati is an Architect with experience in building Cloud Native Microservices architectures, Reactive Systems, Large scale distributed systems, and Serverless Systems. Siva has hands-on in architecture, design, and implementation of scalable systems using Cloud, Java, Go lang, Apache Kafka, Apache Solr, Spring, Spring Boot, Lightbend reactive tech stack, APIGEE edge & on-premise and other open-source, proprietary technologies. Expertise working with and building RESTful, GraphQL APIs. He has successfully delivered multiple applications in retail, telco, and financial services domains. He manages the GitHub( where he put the source code of his work related to his blog posts.

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 )

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: