Search code examples
node.jsnode-mongodb-native

Return counter in db.collection.count()'s callback doesn't work, why?


I want to track the number of documents I have within a collection in a node.js server using mongodb driver. I can insert, delete and update propperly but when I try to count, it works until I try to store that value, moment in which it returns nothing.

Here is my code:

var db_collection = db.collection('collection');

var countCollections = function () {

    var response_count_collections = null;
    db_mensajes.count(function(err,number_of_collections){
        if (err){
            console.log(err);
        } else {
            response_of_collections = number_of_collections;
            console.log('Number of collections: '+number_of_collections);
        }
    });
    return response_count_collections;
};

It logs the number_of_collections correctly but it doesn't return me the right value. In my example it returns null (how I defined my var response_count_collections;) and if I try to return number_of_collections; within the db_collections.count()'s callback like this:

var db_collection = db.collection('collection');

var countCollections = function () {

    var response_count_collections = null;
    db_mensajes.count(function(err,number_of_collections){
        if (err){
            console.log(err);
        } else {
            console.log('Number of collections: '+number_of_collections);
            return number_of_collections;
        }
    });
};

It returns me "undefined". Is there any way to achieve what I want?


Solution

  • Its because it returns the variable before the function is completely executed.

    If you want it to be asynchronous then you will have to learn to control the flow of the program using some node modules like async.

    Update:

    Have a look at this question, it shows how to return value from an async function using callback correctly.