0

I just encountered a strange behavior. I've a MongoDB collection allCustomers and trying to fill it up, as long as the Customers.countDocuments() returns a value lower than 3. Model and Schema are exported and properly accessible, since it's adding the entry by using if, instead of while. Unfortunately that's not my requirement and I it's not reasonable to me.

let Customer = require('./models/customer');

router.get('/', function (req, res) {
    Customer.countDocuments({}, function (err, count) {
        while (count < 3) {
            var emptySlot = new Customer({ name: 'Unused', gender: 'empty' });
            emptySlot.save(function (err, slot) {
                if (err) return console.error(err);
                console.log(slot.name);
            });
          }
        });
        Customer.find({}, function (err, customers) {
            ..
    });
});
Tomblarom
  • 1,429
  • 1
  • 15
  • 38

1 Answers1

1
  1. Where do you initialise the variable count?

  2. Where do you increase the variable count, in order to stop the loop?

  3. Do you know how asynchronous javascript works?

The while loop is a synchronous task, and it will be kept executing until it reaches the end (JavaScript is not multi-threaded). Every asynchronous task that get instanced, will be temporary saved in a event-loop chain and they will be executed, in order, when the synchronous task is completed.

In your case, even if you increase the variable count inside the save callback, the loop will still be infinity. The save callback won't be ever called, since the synchronous task never ends.

The result is that you call save infinity times and you never go out.

A better solution can be implemented using Promise.all