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. :)