rafafan2010 rafafan2010 - 1 month ago 21
Node.js Question

MongoDB `cursor.count` returning 0 despite non-empty collection

I'm trying to retrieve the number of documents in my database that match a certain hash value, but the

count()
function seems to return 0 no matter how many documents are in the collection. This is the code I have:

var cursor = collection.find({hash_val: current_hash_val}, {response: 1,_id: 0});


cursor.count(function(count) {
if(count == 1) {
console.log("Found a unique document. Count is %d",count);
cursor.forEach(function(doc) {
console.log(doc);
});
}
else if(count > 1){
console.log("Found multiple documents. Count is %d", count);
cursor.forEach(function(doc) {
console.log(doc);
});

}
else{
console.log("Did not find any documents. Count is %d", count);
cursor.forEach(function(doc) {
console.log(doc);
});

}
});


I have several documents in the collection that match
current_hash_val
, but my code always jumps to the
else
statement. However, the
forEach
function shows me several records printed to the console. Can someone explain whether I'm using the count function wrong or whether this is incorrect behavior on MongoDB's part?

Answer

It seems it's because the callback function takes two arguments, the error and the count value, so it's assigning the error value that is probably null to count, so try getting the error before the count value on the callback function:

var cursor = collection.find({hash_val: current_hash_val}, {response: 1,_id: 0});


cursor.count(function(err, count) {
    if(count == 1) {
        console.log("Found a unique document. Count is %d",count);
        cursor.forEach(function(doc) {
            console.log(doc);
        });
    }
    else if(count > 1){
        console.log("Found multiple documents. Count is %d", count);
        cursor.forEach(function(doc) {
            console.log(doc);
        });

    }
    else{
        console.log("Did not find any documents. Count is %d", count);
        cursor.forEach(function(doc) {
            console.log(doc);
        });

    }
});

You can check the count example for more info