How to use mongoose with Node

Introduction

Node.js and MongoDB are part of MEAN and MERN stack. The pair is heavily used while building backends for web applications. MongoDB is a NoSQL database and it is quite popular for its simplicity. It is very simple to install and implement. With Node.js, we can easily perform various operations on MongoDB databases. These operations are called CRUD operations that are performed while creating APIs. CRUD is an important part of almost every application. It stands for Create Read Update Delete. To manage the relationship between Node.js and MongoDB, we use a library known as Mongoose. It is an Object Data Modelling(ODM) library for Node.js. Mongoose provides access to MongoDB commands. Using mongoose makes the CRUD more simple and easy. In this article, we will discuss how to use mongoose with Node.js.

Establishing a connection with MongoDB

In the following code, I have already set up a server using Express.js. The name of this file is “server.js”.

const express = require("express");
const app = express();
const router = express.Router();
const port = 4000;

app.use("/", router);

app.listen(port, function() {
  console.log("Server is running on Port: " + port);
});

In the above code, I had already defined the express router. Currently, there is no mongoose. To use mongoose in the Node.js file, first, we have to install it. Open the terminal and go to the folder where server.js is present. Then run the following command to install mongoose.

npm install mongoose

Now, we can import mongoose in the file.

var mongoose = require("mongoose");

The very first use of mongoose in Node is, creating a connection MongoDB database. The following code creates a connection with a database named “details”.

const mongoose = require("mongoose");

var uri = "mongodb://localhost:27017/details";

mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });

const connection = mongoose.connection;

connection.once("open", function() {
  console.log("MongoDB database connection established successfully");
});

Observe the line where the variable uri is declared.

var uri = "mongodb://localhost:27017/details";

The URI is needed in the connect() method. Let’s add this code to the server.js file and check if the connection establishes successfully or not. We will use nodemon to track changes.

Image from Gyazo

Yes! the server is running properly and the connection is established successfully.

Creating schema and model

MongoDB is a schema-less database. We will use mongoose to create a schema in a separate file(model.js). Then we will create a model that takes a schema and create an instance of a document.

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

let employee = new Schema(
  {
    name: {
      type: String
    },
    age: {
      type: Number
    },
    location: {
      type: String
    }
  },
  { collection: "employees" }
);

The schema defines how each document in the collection will look. There will be three fields in each document – name, age, and location. We also specified the collection name in the schema.

{
  collection: "employees";
}

Now, we can call the model constructor and pass the collection name as well as a reference to the schema definition.

module.exports = mongoose.model("Employees", employee);

We have to import it in the server.js file.

var employees = require("./model.js");

Creating an API

We have the instance of the model in our file. The router is already defined. Let’s create an API. We will fetch documents from the details collection. I already added a few documents in it.

Observe the following route handler.

router.route("/fetchdata").get(function(req, res) {});

The above route handler will be invoked when the endpoint ‘/fetchdata’ will be executed.

As mentioned earlier, mongoose allows us to use MongoDB commands in the Node.js file. This makes the job much simpler. In our case, we will use the find() method to fetch all the documents from the details collection. So let’s add it in the route handler. We have to use the instance of the model to call the find() method.

router.route("/fetchdata").get(function(req, res) {
  employees.find({ age: { $lt: 30 } }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Let’s use the postman tool to check if it is working or not.

Image from Gyazo

Yes! It is working perfectly.

Similarly, we can also perform other CRUD operations using mongoose.

Conclusion

We hope you enjoyed this simple demo of how to use mongoose with Node. This is a common architecture and we hope that this article was of some assistance.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.