I have used two return statements inside the function mentioned below. But still function loops for all the users.
module.exports.getByKey = function(key, callback) {
User.find().populate('licences').exec(function(err, users) {
if(err) {
return callback(err);
}
var keyFound = false;
users.forEach(function(user) {
console.log("user found " + user.name);
user.licences.forEach(function(licence) {
console.log("licence found");
if(licence.key == key) {
keyFound = true;
callback(null, user);
return;
}
}, this);
if(keyFound) {
console.log("+++++++++++++++++++++++");
return;
}
}, this);
// return callback({error: "Invalid Key"});
});
}