1

EDIT

I have managed to do it. I have used awesome async module. What follows is the solution:

async.each(req.body.users, function(userId, next) {
  User.count( { _id: userId } ).exec(function(err, count) {
    if(count === null) {
      next("Doesn't exist);
    } else {
      next();
    }
}, function(err) {
  if(err) {
    console.log(err);
  } else {
    console.log("success");
  }
});

QUESTION

My scenario is the following. I am making a post request to the db controller in order to create a document in the db. This request obviously contains data from the form, stored in req.body. I would like to check whether the data is correct before pushing it to the database, and I do so by calling a function to check it.

One of the fields is an array of user._id's and I would like to check whether all of these belong to a user.

The way I implemented this is the following:

req.body.users.forEach(function(userId) {
  User.count({ _id: userId }).exec(function(err, count) {
    if(count === 0) {
      return false;
    }
  }
}
return true;

So basically, I call mongoose to count how many documents in the db have the given id, and if the answer is zero, the field does not contain valid value and the function returns false. Otherwise, it should return true.

The problem is that all the calls to the database are asynchronous, and hence the function returns true before checking all of the user's ids.

I thought of using promises but I have no idea where to start. Does anyone have any ideas or suggestions?

Thanks in advance! Cheers. :)

ficabj5
  • 111
  • 10

1 Answers1

0

So what you want to do is to check that every given idUser is ok.

In my example, I perform a single request that's gonna return every users that have one of the id that's inside req.body.users.

At then end I check if the number of user I wanted to check is the same that the ones I got data for. If it mismatch, it means we have an idUser which is not in database.

  User.find({
      _id: {
        $in: req.body.users,
      },
    }, '_id')
    .then((rets) => {
      if (rets.length !== req.body.users.length) {
        //
        //  /!\ Unknown idUser
        // 

        throw new Error('...');
      }

      // All is alright
    })
    .catch((err) => {
      ...
    });

In my example I used of Promise object, and projection

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69