Every web application needs a database to store information about the users and their activity. A database is an organized collection of data which can be easily accessed, manipulated and updated. There are so many types of the database available in the market but most widely used database are a relational database and NoSQL database.

From last few years, demand for the NoSQL database increases exponentially. Today, Nearly most of the single page web application built with the NoSQL database. When compared to the relational database, NoSQL databases are more scalable and provide excellent performance.

In this article, we will talk about the MongoDB ODM library mongoose and learn how to connect node.js with the MongoDB using the Mongoose ODM library.

What is MongoDB

MongoDB is an open source document based NoSQL database that provides high scalability, high performance. Popular stack like MEAN and MERN uses the MongoDB as a database solution for the web application. It has JSON like document structure and stores all the information as a key-value pair within a document. You can learn more about the MongoDB from their official website.

What is Mongoose

Mongoose is a MongoDB Object Data Modeling(ODM) library. It provides the relationship between data and validation. This ODM and database combination is most popular in the javascript developer community. It allows us to have MongoDB CRUD command in an easy and simple way.

To use mongoose into your application, you can install it easily by using the below npm command

npm install mongoose --save

Connect Mongoose With the Node.js Application

Now, we have installed mongoose in our application, we just have to connect it with the application backend API.

Before connect the mongoose with the node.js first, make sure you have installed node.js and created a server using the node.js.

We can get all the feature of mongoose by adding below line

const mongoose = require('mongoose');

Now we have include the mongoose in our application, let’s connect it with the database by using the below line of code

mongoose.connect('mongodb://localhost/mongoose_demo');

The connect function accept two other optional parameters. The first one is to provide username and passowrd and second one is a callback function. Callback function can be used in one of the two ways:


//without using the promise
mongoose.connect(uri,options,function(err){
   //check error in the initial connection
});

//with using the promise
mongoose.connect(uri,options).then(() => {
  //connection established successfully
}).catch(error){
  //catch any error during the initial connection
}

If everything is ok then mongoose is now set up and connected with the provided database name. Now, let’s move on to define the mongoose schema for the database.

Defining a Mongoose Schema

Before going to use database, we have to define our schema. Thease schemas will work as a constructor which can be saved and retrived from our database.

Let’s define an example schema for this article which is call as User.

let userSchema = mongoose.Schema({
        name: String,
        email: String
});

You can define your schema like above and provide the attribute for the schema. mongoose allowed below schema types:

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

The schema which we defined earlier is very simple. In real projects, there are a lot of things which need to define in the schema like validation, required parameter and other things.

We can create the mongoose model by using the below line of code

let User = mongoose.model('User', userSchema);

Now our schema is created,we can use it in other places by exporting it

// make this available to our Node applications
module.exports = User;

Till now, we leran how to connect the mongoose and how to create a schema for our application. Now, let’s learn how we can perform the CRUD operations on our created schema.

Create A New User

Mongoose provide built-in function save to insert the data into our documents.

// include the user model
let User = require('path_to_your_model/user');

// create a new user
let newUser = User({
  name: 'demo',
  email: 'demo@demo.com'
});

// save the user
newUser.save(function(err) {
  if (err) throw err;
  console.log('User created successfully.');
});

Read User Data

There are so many functions available in the mongoose to read the data from the database. Here we will learn only the most used function.

Read all the user data

// get all the users
User.find({}, function(err, users) {
  if (err) throw err;

  // object of all the users
  console.log(users);
});

Read single user data

// get the user data with email demo@demo.com
User.find({ email: 'demo@demo.com' }, function(err, user) {
  if (err) throw err;

  // object of the user
  console.log(user);
});

Read user by its ID

// get a user with ID of 5acdghuugd125j
User.findById('5acdghuugd125j', function(err, user) {
  if (err) throw err;

  // show the one user
  console.log(user);
});

Update the User Data

Mongoose also provide lots of function to update the data of the schema. Here we will only listed most used function.

Find by ID and Update

// find the user with id 5acdghuugd125j
// update email to demo_test@demo.com
User.findByIdAndUpdate('5acdghuugd125j', 
    { email: 'demo_test@demo.com' }, 
    function(err, user) {
      if (err) throw err;

    // updated user
    console.log(user);
});

Find and Update

// find the user demo@demo.com
// update email to demo_test@demo.com
User.findOneAndUpdate(
    { email: 'demo@demo.com' }, 
    { email: 'demo_test@demo.com' }, 
    function(err, user) {
      if (err) throw err;

      // we have the updated user returned to us
      console.log(user);
});

Delete User Data

Find and Delete

// find the user with email demo@demo.com
User.findOneAndRemove(
    { email: 'demo@demo.com' }, 
    function(err) {
      if (err) throw err;

      // we have deleted the user
      console.log('User deleted successfully.');
});

Find by ID and Delete

// find the user with id 5acdghuugd125j
User.findByIdAndRemove('5acdghuugd125j', function(err) {
  if (err) throw err;

  // we have deleted the user
  console.log('User deleted successfully');
});

Conclusion

After reading this article, you should be able to connect Node.js application with the MongoDB using mongoose ODM library. Apart from the connection, you are now able to perform the CRUD operation on mongoose schma.

I would suggest you to follow the Mongoose official documentation which will provide your more topics in details. If you have any doubt or any suggestion regarding this article then comment below.

Pin It