0

I need to write a function that return the number of documents in a collection using Node.js. This is my code (I've followed the advice found in another question):

async function countCollections(callback) {
  MongoClient.connect(url, function(err, db) {
    if (err) callback(error);
    var dbo = db.db(nameDB);
    dbo.collection(nameCollections).find(query).count(function(err, count) {
      if (err) callback(error);
      db.close();
      callback(null, count);
    });
  });
}

I call this function in this way:

await countCollections(function(err, count) {
    if (err) {
        return console.log(err.message);
    }
    console.log('Number of documents: ', count);
});

Using this method, I can just view the count value, but I can't directly use. How can I do to obtain into a variable the count value when I call the function?

InfT
  • 41
  • 7

1 Answers1

0

You can use Mongo's [countDocuments] method.(https://docs.mongodb.com/manual/reference/method/db.collection.countDocuments/).

let count = await db.collection(nameCollections).countDocuments(query)

Also without really knowing how your app works i recommend you don't open a new Mongo connection every time the function calls but to open it once when your app starts.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
  • Thank you, but it would seem not to work. Could you be more precise? And how can I connect to Mongo just one time? – InfT Dec 02 '19 at 15:27
  • Again i'm unsure how your app looks but in theory you connect to mongo when you start your app then you either pass the connection as a parameter between functions or better yet have a "helper" class that holds the client and can give it to anyone who asks. – Tom Slabbaert Dec 02 '19 at 16:08