simba777
simba777

Reputation: 81

Unable to push into empty Array JS

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.

Upvotes: 0

Views: 629

Answers (2)

tymeJV
tymeJV

Reputation: 104775

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

Upvotes: 1

TuanNguyen
TuanNguyen

Reputation: 1046

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.

Upvotes: 0

Related Questions