Do something if nothing found with .find() mongoose
When there are no matches find() returns []
, while findOne() returns null
. So either use:
Model.find( {...}, function (err, results) {
if (err) { ... }
if (!results.length) {
// do stuff here
}
}
or:
Model.findOne( {...}, function (err, result) {
if (err) { ... }
if (!result) {
// do stuff here
}
}
I had to use:
if(!users.length) { //etc }
to get it to work.
UserModel.find({ nick: act.params }, function (err, users) {
if (err) { console.log(err) };
if (!users.length) { //do stuff here };
else {
users.forEach(function (user) {
console.log(user.nick);
});
}
});
is what I found to work.