Warm tip: This article is reproduced from stackoverflow.com, please click
mongodb mongoose

MongoDB countDocuments() is returning an object, not a number

发布于 2020-04-07 10:22:28

I'm starting to learn about mongoose/MongoDB aggregation functions, and am having some basic difficulties. For example, I'm trying to do the following:

var myModels= require('./models/myModel');
var myCount = myModels.countDocuments({userID: "A"});
console.log(myCount );

I just want to count the number of documents with userID of "A" but when this prints to the console, it's printing as a whole object, instead of just a numerical count. I've read the answer here but I'm still not able to solve this problem (also, is there a way, unlike in that question, to return the count directly rather than having to predefine a variable and set it in a callback function?)

I'm trying to follow the guide here and don't see where I'm going wrong.

Questioner
garson
Viewed
71
tom slabbaert 2020-02-01 02:47

It's because the return value of countDocuments is a promise and not a number.

You either need to wait for that Promise or use callback syntax like so:

var myModels= require('./models/myModel');
// this required the code to be inside an async function
var myCount = await myModels.countDocuments({userID: "A"}); 
console.log(myCount);

Or:

var myModels= require('./models/myModel');
myModels.countDocuments({userID: "A"})
     .then((myCount) =>{console.log(myCount);});