get length of all documents in collection mongoose

Viewed 104

I am trying to get the count for how many documents I have in my collection. I have this, but it is not returning what I need it to, it is returning a whole bunch of unnecessary info I don't need for this simple task:

var estimatedDocumentCount = ServicesModel.countDocuments({});
console.log(estimatedDocumentCount)

It is returning the entire query, plus all its embedded parameters it seems like. how do I do this properly?

2 Answers
async function countDocuments() {
  const count = await ServicesModel.countDocuments({});
  return count;
};

const count = countDocuments();

It's probably because countDocuments is an asynchronous call and you are executing it synchronously.

Follow the syntax mentioned in Mongoose Docs which uses a callback function to get the count.

ServicesModel.countDocuments({}, function (err, count) {
  console.log(count);
});
Related