How to Use the Mongoose Find Method

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

Introduction

Out of all the CRUD operations, retrieving data is most commonly used. There are many methods retrieving data from MongoDB when using mongoose. One of the most popular methods is the find() function. The find() function retrieves all the existing documents in a collection. We can also specify queries and projections to get the desired output. In this article, we will discuss how to use the Mongoose find method.

We will use the kennels collections for demonstration.

1
2
3
4
5
{ "_id" : ObjectId("5db6b24830f133b65dbbe457"), "name" : "Rambo", "age" : 3, "breed" : "Labrador" }
{ "_id" : ObjectId("5db6b25b30f133b65dbbe458"), "name" : "Max", "age" : 2, "breed" : "German Shephard" }
{ "_id" : ObjectId("5db6b26730f133b65dbbe459"), "name" : "Spike", "age" : 3, "breed" : "Labrador" }
{ "_id" : ObjectId("5db6b27530f133b65dbbe45a"), "name" : "Tyke", "age" : 4, "breed" : "Pitbull" }
{ "_id" : ObjectId("5db6b28d30f133b65dbbe45b"), "name" : "Romeo", "age" : 2, "breed" : "Labrador" }

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

find()

Observe the following function. The following route will be invoked when the endpoint ‘/getData’ is executed.

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

We can see, the find() function has two parameters – an empty object and a callback function. The empty object is for the query part (condition) and we will discuss it soon. In this above function, there is no condition. The second parameter is a callback function. This callback function has, in turn, two parameters – an error(if any occurs), and the result of the find() function. Let’s execute this route using the postman tool and see what is the output.

Image from Gyazo

As mentioned earlier, the result is an array that contains all the documents present in the collection.

find() with query

Above, we passed an empty object to the find() function. This empty object denotes the query. This query is the condition according to which the resulting documents will be filtered. Suppose we want to get only those documents where the breed is ‘Labrador’. Let’s see how can we do this.

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

There is only one difference, the empty object is replaced.

1
{"breed" : "Labrador"}

This means, only those documents will be present in the output where the breed is ‘Labrador’. Let’s check.

Image from Gyazo

Yes! the find() function returns only those documents where the breed is ‘Labrador’.

Note: It is always mandatory to provide the query part. If there is no condition, pass an empty object.

find() with query and projection

The find() function provides one more option to modify the output. Check the number of fields in each document when we used the query.

Image from Gyazo

All the fields are present in every object along with the auto-generated _id field. But what if we want only the name field. Suppose, we want all the documents where the breed is ‘Labrador’ and we want only the name field of those documents. We can use the projection in such a case. Let’s see how can we use projection with find() function.

1
2
3
4
5
6
7
8
9
router.route("/getData").get(function(req, res) {
  kennels.find({ breed: "Labrador" }, { name: 1 }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Check the second parameter.

1
{"name" : 1}

When we specify a single parameter between the query part and the callback function, it denotes the projection. Here, we add an object, and the fields specified in it will be displayed in the output. All other fields will be ignored. Let’s check.

Image from Gyazo

Yes, the age and breed fields are not present in the output, but the auto-generated _id field is there. To ignore this field also, just make the following change in the projection part.

1
{"name" : 1, "_id": 0}

Let’s check the output now.

Image from Gyazo

This is exactly what we expected!

Conclusion

Thank you for reading this article on how to use the Mongoose find method. We hope you can apply what you’ve learned to your specific application.

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.