Categories
JavaScript Answers

How to check if ID exists in a collection with Node Mongoose?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.