kukko
kukko

Reputation: 653

Return document count with mongoose in NodeJS

How can I return the count of documents returned by a query? I have a routing file, which have the following code:

router.post('/facebookLogin', function(req, res, next){
    var User=require('../models/user');
    var a=User.facebookUserExist(req.body.id, req.body.email);
    console.log(a);
    res.end();
});

And here is the content of the User model file:

var User=function(data){
    this.data=data;
}
User.prototype.data={};
User.prototype.facebookUserExist=function(id, email){
    var output;
    db.collection('users').find({
        $or:[
            {
                facebookID:id
            },
            {
                email:email
            }
        ]
    }).count(function(err, numOfDocs){
        output=numOfDocs;
    });
    return output;
}
module.exports=new User;

I set the value of the output variable in the count method callback, but the function still return undefined.

Upvotes: 2

Views: 5189

Answers (2)

Arpit Yadav
Arpit Yadav

Reputation: 545

.count() is required to get total docs in MongoDB. It might help.

USER.find(req.body.id, req.body.email).count(function(err, count) {
    console.log("Number of docs: ", count); });

Upvotes: 1

Arif Khan
Arif Khan

Reputation: 5069

We know that JavaScript is asynchronous and won't wait for result. So you may either use callback or Promise object, here is example of callback for your code

router.post('/facebookLogin', function(req, res, next){
    var User=require('../models/user');
    User.facebookUserExist(req.body.id, req.body.email, function(err, count)
        if(err)
            console.log('Error ', err);
        else
            console.log(count);
        res.end();
    });
});

and your User model take a callback as last argument

var User=function(data){
    this.data=data;
}
User.prototype.data={};
User.prototype.facebookUserExist=function(id, email, callback){
    var output;
    db.collection('users').find({
        $or:[
            {
                facebookID:id
            },
            {
                email:email
            }
        ]
    }).count(function(err, numOfDocs){
        callback(err, numOfDocs);
    });
    //return output;
}
module.exports=new User;

Upvotes: 1

Related Questions