Alexander Ceballos
Alexander Ceballos

Reputation: 760

Retrieving value of count mongodb collection in a variable

I am trying to retrieve the value of records from a collection in Mongo DB

Here is my source.

exports.procc = function(req, res) {

        db.collection('search', function(err, collection) {
                    collection.count({'str':'car'},function(err, count) {
                       console.log(count+' records');//Prints 2 records
                       c=count;     
                    });
        });
        console.log('records= '+c);//print 0 records
 res.end();
};

The problem is that out of the callback prints the number of the register, but out of the callback prints 0 and I don't know how to save that value in a variable.

Upvotes: 2

Views: 1648

Answers (2)

Alexander Beletsky
Alexander Beletsky

Reputation: 19821

You code does not respect async nature of node.js IO.

exports.procc = function(req, res) {
        db.collection('search', function(err, collection) {
                    collection.count({'str':'car'},function(err, count) {
                       console.log('records= ' + count);//print 0 records
                       res.end();
                    });
        });
};

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311935

Because db.collection and collection.count are asynchronous methods, the c variable is getting set after the second console.log statement is executed.

So anything you want to do with c has to occur within the collection.count callback.

Upvotes: 1

Related Questions