0

The findOne query is returning a user from the DB. When i console.log(user) it does print out user data. But for some reason isn't pushing into user_contacts. Its just returning as an empty array.

get_contacts: function (req, res){
                var user_contacts = [];
                for(var i=0;i<req.body.contacts.length;i++){
                    User.findOne({_id: req.body.contacts[i]._User}, function (err, user) {
                        if(user){
                            console.log(user);
                            user_contacts.push(user);
                        }else{
                            console.log("Error");
                        }
                    })  
                }
            console.log(user_contacts);
            res.json(user_contacts);
            }

This should be so simple, but just cannot see what I am doing wrong. Appreciate the help.

2
  • 1
    The DB call is async - when you call res.json your DB calls haven't executed yet - hence the empty response. Commented Feb 23, 2016 at 1:57
  • but the console.log(user) is still printing out the user data, if the DB calls haven't executed how can I have user data to print? Commented Feb 23, 2016 at 2:10

2 Answers 2

1

Since the call is async - your logs and response are executed before everything is finished. You'll probably also run into some issues with looping that async call - your best bet is to use $in and then return:

get_contacts: function (req, res){
    var ids = req.body.contacts.map(function(contact) { return contact._User });
    User.find({_id: {$in: ids}}, function(err, users) {
        res.json(users)
    });
}
Sign up to request clarification or add additional context in comments.

4 Comments

will this not return only one single user data? .. I am trying to retrieve multiple users data together. Thus created the empty array and tried pushing.
This will query all the ids of the users passed back and return an array @Ani777
tried it, it works. Thanks a lot. so basically whats happening is ids is returning all the _User fields in req.body.contacts and the the Query is searching for users with the ids that have been returned. Am i right? will be reading about $in as well.
@Ani777 -- Yep - that's exactly what's happening
0

User.findOne({}) is async, which mean the callback function where you push data into user_contacts array is executed with delay. Therefore, the moment you console.log, user_contacts is still empty.

1 Comment

Thanks for the link to async, reading it right now, hope can make some sense out of it.

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.