2

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.

1
  • 2
    1. you don't need to use find and count, you can use just count with the same filter. 2. you are using a callback method as an async method, that's why you get the undefined. Commented Oct 2, 2016 at 11:36

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

I can't make the code to wait for a functions return value?
When I try to use promise object, it is always in pending state and the then method not executing.
@kukko return statement won't wait for you function completion. You may use either callback( as I explained in my answer) or Promise object
1

.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); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.