Fetching Data from MongoDB using get in mongoose

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

As we all know, a database is used to store data. But it is not just that. We always don’t have static data. After setting up a database, we may need to perform many operations. We may need to add more data, or we need all the data or some data. We may also need to update the data or even remove the data. These are the CRUD operations. It is an acronym that stands for Create, Read, Update, and Delete. Each kind of database has its own ways of performing CRUD operations.

One of the most frequently used CRUD operations is the Read operation. The Read operation is used to retrieve data from a database. We can retrieve all the data at once or some of the data, according to the requirements. In this article, we will discuss fetching data from MongoDB using get in mongoose.

We will use the $in method on the kennel collection.

1
2
3
4
5
6
7
8
{ "_id" : ObjectId("5dde131c7ece3115a2fbe600"), "name" : "Rambo", "age" : 5, "breed" : "Pitbull" }
{ "_id" : ObjectId("5dde135c7ece3115a2fbe601"), "name" : "Spike", "age" : 4, "breed" : "German Shephard" }
{ "_id" : ObjectId("5dde136e7ece3115a2fbe602"), "name" : "Maxi", "age" : 2, "breed" : "Pitbull" }
{ "_id" : ObjectId("5dde137b7ece3115a2fbe603"), "name" : "Tyke", "age" : 3, "breed" : "Great Dane" }
{ "_id" : ObjectId("5dde139b7ece3115a2fbe604"), "name" : "Leo", "age" : 2, "breed" : "German Shephard" }
{ "_id" : ObjectId("5dde13cb7ece3115a2fbe605"), "name" : "Romeo", "age" : 2, "breed" : "Doberman" }
{ "_id" : ObjectId("5dde13e97ece3115a2fbe606"), "name" : "Julie", "age" : 1, "breed" : "Pug" }
{ "_id" : ObjectId("5dde140c7ece3115a2fbe607"), "name" : "Scooby", "age" : 3, "breed" : "Great Dane" }

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

Fetching data

To fetch data, we have to make a GET request. But before moving further, we need a NodeJs file with mongoose and express imported into it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var mongoose = require("mongoose");
const express = require("express");
const app = express();
var port = 4000;
var kennel = require("./model.js");
const router = express.Router();
var uri = "mongodb://127.0.0.1:27017/kennel";

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(port, function() {
  console.log("Server is running on Port: " + port);
});

Let’s run it using mongoose.

Image from Gyazo

So the server is running properly. Now, have a look at the line where we created an instance of the router.

1
const router = express.Router();

A router is used for route handling. We will create a router handler which will have the GET method attached to it. This router handler will also contain an endpoint that needs to be executed to invoke the route handler. To use the router, we have to use the use() method, which is already defined in the NodeJs file.

1
app.use("/", router);

Let’s create the route handler. We will need the instance of a router for this.

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

Have a look at the above route handler. The route() method is used. The parameter of the route() method is an endpoint. In our case, it is ‘/fetch’. The GET method is attached to it. There are three other methods and they are also attached in the same way. The GET method has one parameter – a callback function. This callback function, in turn, has two parameters – request and response.

This is how a GET request is made in mongoose. But currently, this will do nothing. We have to specify a method to fetch the data from the database. There are several methods. We will use the most common one, the find() method.

1
2
3
4
5
6
7
8
9
router.route("/fetch").get(function(req, res) {
  kennel.find({}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

We have used the response of the GET request (res) to send the result or error of the find method. Let’s execute it using the postman tool.

Image from Gyazo

Yes! It fetches all the documents of the kennel collection.

Conclusion

In this article we have showed you how to use mongoose on top of MongoDB with the express framework in NodeJS to create a API route that returns data from the database. We hope this helpful to you and please don’t hesitate to contact us at Object Rocket with any database needs.

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.