To check if ID exists in a collection with Node Mongoose, we call the countDocument
method.
For instance, we write
User.countDocuments({ _id: userID }, (err, count) => {
if (count > 0) {
//...;
}
});
to call countDocuments
with an object with _id
set to the value we’re looking for.
The count
parameter in the callback has the number of items with the _id
value.