Easy to follow mongoose example with NodeJS

Introduction

In this article, we will discuss an easy to following mongoose example with NodeJS. We will create four API endpoints in NodeJS and mongoose, each of them performing certain CRUD operations on a MongoDB database.

Setup connection

So let’s start by setting up a server and a connection with the MongoDB database.

var mongoose = require("mongoose");
const express = require("express");
const app = express();
var kennel = require("./model.js");
var uri = "mongodb://127.0.0.1:27017/petstore";
const router = express.Router();
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });

const connection = mongoose.connection;

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

app.use("/", router);
app.listen(4000, function() {
  console.log("Server is running on Port: 4000");
});

In the above code, a server is created using Express.js. The server will run on port 4000. Also, a connection with the database “petstore” is established using mongoose. The following URI is used.

var uri = "mongodb://127.0.0.1:27017/petstore";

Setup the Schema

We also need the router middleware to create route handlers. I had already added it to the above code. Schema is also defined in a separate file name “model.js”.

let kennel = new Schema(
  {
    name: {
      type: String
    },
    age: {
      type: Number
    },
    breed: {
      type: String
    }
  },
  { collection: "kennel" }
);

This is how each document in the kennel collection will look. Each document will have three fields – name, age and, breed. We need the instance of the model in our main file, so I had already imported it.

Let’s run the server.

Image from Gyazo

Everything is working fine. We can proceed further.

Inserting documents in the collection

So, we start by inserting data into the kennel collection. We need a route handler. We can create it using the router we defined earlier in our NodeJS file.

router.route("/insertData").post(function(req, res) {});

This route handler will be invoked when the endpoint ‘/insertData’ is executed. As it is a Create operation, we will make a post request. The callback function has two parameters – request(req) and response(res).

We will use the insertMany() method to insert the following documents in the collection.

var docs = [
  {
    name: "Rambo",
    age: 3,
    breed: "Pitbull"
  },
  {
    name: "Scooby",
    age: 5,
    breed: "Great Dane"
  },
  {
    name: "Johnny Boy",
    age: 2,
    breed: "Pugg"
  }
];

As the name suggests, the insertMany() method of mongoose is capable of inserting multiple documents in a collection. So let’s add this method in the route handler.

router.route("/insertData").post(function(req, res) {
  var docs = [
    {
      name: "Rambo",
      age: 3,
      breed: "Pitbull"
    },
    {
      name: "Scooby",
      age: 5,
      breed: "Great Dane"
    },
    {
      name: "Johnny Boy",
      age: 2,
      breed: "Pugg"
    }
  ];

  kennel.insertMany(docs, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

The array of objects that we defined earlier is to be passed as the first parameter of the insertMany() method. The second parameter of this method is a callback function. It has two parameters – an error (if any occurs) and the result. We will use the postman to for testing. You can download it from www.getpostman.com.

So let’s try this route using postman tool.

Image from Gyazo

The insertMany() method returns all the documents that were inserted in the collection. Next, we will create an API that will fetch these documents from the collection.

Fetching documents from the collection

Let’s create another route handler that will make a GET request.

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

There are various methods to fetch documents from a collection. Each method fetches data in its own way. We will use the find() method. The find() method fetches all the documents from a collection.

router.route("/fetchData").get(function(req, res) {
  kennel.find({}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

The first parameter of the find() method is the query. Documents are filtered according to the condition(s) provided in the query. In our case, we are only providing an empty object. With an empty object, the find() method returns all the documents present in the collection. Let’s execute this route using postman tool.

Image from Gyazo

Updating documents

Another important CRUD operation is the Update operation. An updating operation should be handled with proper care. A single mistake can lead to many problems in the backend. Let’s create another route handler to update a document.

router.route("/updateData").put(function(req, res) {});

The above route handler will make a PUT request. Mongoose provides several methods for updating as well. We will use the updateOne() method. The updateOne() method matches a single document according to the query and then updates it. We have three documents in the kennel collection. We will update the name field of the document where the value of the breed field is “Pugg”. Let’s do it.

Image from Gyazo

It returns an object. The value of the nModified field is 1. This means, one of the document was updated. Let’s use the API we created earlier to check if the document was updated or not.

Image from Gyazo

Yes! The document where the value of the breed field is “Pugg” is updated.

Deleting documents

Similar to the Update operation, the Delete operation should also be handled carefully. There are two important delete method in mongoose – deleteOne() and deleteMany() method. The deleteOne() method is used to delete a single document and the deleteMany() method is used to delete multiple documents. We will use the deleteMany() method to delete all the documents in the kennel collection.

router.route("/deleteData").delete(function(req, res) {
  kennel.deleteMany({}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

The above route will make a DELETE request. Let’s add the deleteMany() method in it.

router.route("/deleteData").delete(function(req, res) {
  kennel.deleteMany({}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Similar to the find() method we used earlier, here also we will pass any empty object as the query to delete all the documents. Let’s execute this route using the postman tool.

Image from Gyazo

It returns an object. The value of the deletedCount is 3. This means three documents were deleted.

Conclusion

This was a simple mongoose example with NodeJS. We discuss all the CRUD operations with simplicity. The methods we used are simple and easy to use. Although, there are several more methods in mongoose but these methods are used commonly with mongoose.

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.