0

I have one problem regarding return value of count function of db.collection.find.count(); namely my program should return integer value (number of documents in db.collection by certain criteria), but function returns Promise which I don't know how to use in callback function.

I tried to make callback function inside count() method like count(function(err,res){ if(err) console.log('Error') else count1=res;}),but it doesnt work. i also searched stackoverflow and mongodb documentation, and tried some other solutions but it didn't help also. (but when i tried db.collection('blogCollection').find("author":"user123").count() in robomongo, it correctly ran and displayed result of query)

This is my code var count1=database.collection("blogCollection").find({"author":id}).count();

where count1 should be the number of documents where author field equals to id value. Thank you in advance for helping.:) My mongodb is 3.2 version, and node is v10.15.3.

slomil
  • 193
  • 1
  • 4
  • 12

2 Answers2

0

Promises and callbacks have different syntaxes. You can check how Promise works here. You may also want to check the difference with callbacks here.

In your case, you can use a Promise like here:

database.collection("blogCollection").find({"author":id}).count()
  .then((count1) => {
    console.log(count1);
});

You can also opt to use ES6 Async/Await:

async function count() {
  const count1 = await database.collection("blogCollection").find({"author":id}).count();
  console.log(count1);
}

Note the async before the function, and the await before calling the database function.

juancito
  • 866
  • 2
  • 9
  • 22
0

theres should be multiple callbacks within your code not just at the end

refer to this Callback at MongoDB Operation With Node.js

as well as the count function for the node driver doesnt need to operate on a cursor http://mongodb.github.io/node-mongodb-native/3.2/api/Collection.html#count

so your code should really look like

database.collection("blogCollection", (err, col) => {
    col.count(query,opt,  (err,count )=> count1 = count)
)

with async await

const col = await database.collection("blogColelction")
const count1 = await col.count(query, opt)
Pita
  • 1,444
  • 1
  • 19
  • 29