developerg1000
developerg1000

Reputation: 121

get length of all documents in collection mongoose

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?

Upvotes: 1

Views: 622

Answers (2)

Simon
Simon

Reputation: 167

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

const count = countDocuments();

Upvotes: 2

tbking
tbking

Reputation: 9056

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);
});

Upvotes: 1

Related Questions