Mongoose Find All

Introduction

When working with databases, data retrieval is the most used operation of all the CRUD operations. When working with mongoose and MongoDB, documents of a collection can be retrieved using various methods. In this article, we will discuss such methods of retrieving documents from a collection in MongoDB. Let’s jump in and learn how to use Mongoose to find all documents.

We will work on the details collection. It contains the following five documents.

{ "_id" : ObjectId("5d9d95c72116d7e2e2d5b4c7"), "name" : "John", "age" : 21 }
{ "_id" : ObjectId("5d9d95db2116d7e2e2d5b4c8"), "name" : "Sam", "age" : 23 }
{ "_id" : ObjectId("5d9d95e32116d7e2e2d5b4c9"), "name" : "Lisa", "age" : 28 }
{ "_id" : ObjectId("5d9d95f72116d7e2e2d5b4ca"), "name" : "Ronn", "age" : 21 }
{ "_id" : ObjectId("5d9d95ff2116d7e2e2d5b4cb"), "name" : "Max", "age" : 29 }

We have the following route. We will write methods in the handler.

router.route("/find").delete(function(req, res) {});

And we will use the postman tool for executing routes. You can download this tool from https://www.getpostman.com/.

find()

The most common method for data retrieval in both mongoose, as well as mongo shell, is the find() method. The find methods retrieve all the documents of a collection when an empty object is passed. Let’s try.

router.route("/find").get(function(req, res) {
  detail.find({}, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json(result);
    }
  });
});

The find() method has two parameters – an object and a callback function. Here, we are passing an empty object. The callback function also has two parameters – error (if any occurs) and the returning value.

Let’s take a look at the output using the postman tool.

Image from Gyazo

As mentioned earlier, the find() method returns all the documents when an empty object is passed. Let’s pass a condition.

router.route("/find").get(function(req, res) {
  detail.find({ age: 21 }, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json(result);
    }
  });
});

This time we passed an object ({“age” : 21}). Now the find() method will return only those documents where age is 21. Let’s take a look at the output.

Image from Gyazo

But did you notice one thing? The find() method returns all the fields of a document. We can also modify the fields in the output. Suppose we want only the name field of all the documents in the collection. There is an optional parameter of the find() method that is passed as the second parameter before the callback function. It specifies which fields should be present in the output. Let’s try.

router.route("/find").get(function(req, res) {
  detail.find({}, { name: 1 }, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json(result);
    }
  });
});

This time, we passed an empty object and then a second object.

{
  name: 1;
}

This means only the name field will be present in the output. Let’s see the output.

Image from Gyazo

The age field is ignored in the output. But still, we can see the auto-generated _id field in the output. We can omit the _id field by using the following line of code.

{name: 1, _id:0}

Now only the name field will be present in the output.

Image from Gyazo

findOne()

Unlike the find() method, the findOne() method returns only one document. If an empty object is passed to the findOne() method, it returns the very first document of the collection. Let’s try.

router.route("/find").get(function(req, res) {
  detail.findOne({}, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json(result);
    }
  });
});

Let’s check the output.

Image from Gyazo

We can see there is only one document in the output and this is the very first one.

Let’s pass a condition.

router.route("/find").get(function(req, res) {
  detail.findOne({ age: 21 }, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json(result);
    }
  });
});

This time we passed an object to the findOne() method ({ “age” : 21}). It will return only the first document that matches the condition. All other documents that match the condition will be ignored.

Image from Gyazo

findById

Apart from find() and findOne() methods, there is one other method that specifically finds a document according to the value of the _id field. This method is called findById() method. The value of _id is always unique in a collection. So the findById() method only returns a single document. Let’s try this method.

router.route("/find").get(function(req, res) {
  detail.findById({ _id: "5d9d95f72116d7e2e2d5b4ca" }, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json(result);
    }
  });
});

Image from Gyazo

If we pass an empty object to the findById() method, it will cause an error.

Conclusion

So we discussed three methods for retrieving data from MongoDB in mongoose. The find() method is most commonly used because it gives us more options. People usually confuse the find() method for the findAll() method. But there does not exist any such method in mongoose. The find() method can be used for retrieving all the documents from a collection. The findOne() and findById() method returns only a single document, but still are very useful. So we have a few options for data retrieval in 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.