Mongoose Query Inside Loop

Introduction

Using loops for iteration is one of the most common parts of programming and development. The for loop, while loop and do-while loop are the most commonly used loops in the programming and development world. We can also use them in mongoose too. In this article we’ll discuss how to use a Mongoose query inside a loop.

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

query in loop

Let’s go with the most basic method for iteration – the for loop. In the for loop, we initialize a variable, give a condition and increment/decrement the variable.

Let’s insert an object three times using the for loop. Right now, the details collection does not contain any documents.

router.route("/test").get(function(req, res) {
  for (var i = 0; i < 3; i++) {
    detail.create({ name: "John", age: 21 }, function(err, result) {
      if (err) {
        console.log(err);
      } else {
        res.json(result);
      }
    });
  }
});

Let’s execute this route using the postman tool and see what is the output.

Image from Gyazo

It returns the object we passed to the create method. How many documents do you think are added in the details collection? Let’s see through the mongo shell.

> db.details.find()
{ "_id" : ObjectId("5d9e2549ed42d64a109d1fe4"), "name" : "John", "age" : 21, "__v" : 0 }
{ "_id" : ObjectId("5d9e2549ed42d64a109d1fe6"), "name" : "John", "age" : 21, "__v" : 0 }
{ "_id" : ObjectId("5d9e2549ed42d64a109d1fe5"), "name" : "John", "age" : 21, "__v" : 0 }
>

As expected, three documents with the same values are inserted. This is how we can add documents using a for loop. But you can also see, an extra field (__v) is added while using this method.

But lets the console for a moment.

Image from Gyazo

This happens because we are sending a response multiple times (because of the for loop). This is not allowed. We can remove the “res.json(result)” line and everything will work fine.

But it is not recommended to use queries inside a loop because of the asynchronous behavior of Nodejs. So it is better to avoid using queries in loops. It can result in unwanted errors.

Conclusion

Using loops and queries together is a bad idea. For most of the part, Nodejs is asynchronous and loops do not work well with asynchronous behavior. So avoid loops if there are queries involved.

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.