2

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.

garson
  • 1,505
  • 3
  • 22
  • 56
  • 2
    Follow the pattern given in the question you cite. Like most stuff in Node this is an /asynchronous/ call, so the value you want possibly doesn't even exist when the function returns. If you don't pass a callback, you get a promise; use `.then` and `.catch` on the object you get back, etc. – BadZen Jan 31 '20 at 18:37
  • As @BadZen says, take a look https://mongoosejs.com/docs/api.html#model_Model.countDocuments – Valijon Jan 31 '20 at 18:37

1 Answers1

7

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);}); 
Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
  • Thank you, I'm trying this. For the second example, I'm getting an error that await is not valid - that should still include "await" right? – garson Jan 31 '20 at 18:46
  • 1
    Nope, the await resolves the promise, which is the same action `.then()` does. – Tom Slabbaert Dec 29 '21 at 17:31