-1

I want to save the amount of documents of a collection in "const amount_documents". As described in this question: How to get all count of mongoose model? you can not simply write

const amount_documents = User.count();

What is the correct way to do this? When I use this code:

  var myCallback = User.count({}, function(err, count) {
    callback(count);
  });

it says "callback is not defined"

egjada
  • 119
  • 2
  • 12
  • Where do you define `callback`? I suspect your functionis running correctly but just doesnt have a callback reference. Thry this and see: `var myCallback = User.count({}, function(err, count) { console.log(count); });` – Sello Mkantjwa Sep 13 '17 at 14:49

1 Answers1

1

User.count is asynchronous, with this syntax, you have to execute your code in a callback, this way :

  User.count({}, function(err, count) {
    const amount_documents = count;
    // your code using the count
  });

If you are using promise and await/async syntax, you can do it like this :

const amount_documents = await User.count({});
// Your code using the count here
Julien TASSIN
  • 5,004
  • 1
  • 25
  • 40