Cannot add properties to an object – Node.js/Mongoose

I am trying to check if a user account has already been created in either User model or TempUser model, however encounter an issue where I cannot add a found value to an object in order to process the conditional check.

Please check the code below and comments:

exports.isRegistered = function(userModel, tempUserModel, username){
    var obj = {}; //creating an empty object to add the found results later
    userModel.findOne({username: username}, function(err, user){
        if(err) throw err;
        if(user){
            obj.user = user;
            console.log(obj); // doesn't fire as no user was found found
        }else{
            tempUserModel.findOne({username: username}, function(err, tempUser){
                if(err) throw err;
                obj.tempUser = tempUser;
                console.log(obj); // returns object with a tempUser as it was found
            });
        }
    });
    console.log(obj); //returns an empty object again.
};

Answer

After seeing the code and your issues, I can come these conclusions:

doesn’t fire as no user was found found

Are you sure you User collections has these object with given username? I don’t think so. Please check if you’re providing the correct value of username and a doc exists in User collection with that value.

returns an empty object again.

Callbacks are always a little tricky to understand. Ok, so let’s break the steps you did in your code:

  1. Declared obj, as blank object
  2. Called findOne on a model
  3. Logged obj, which showed you {},i.e, blank object

It happened because 2nd step ran Asynchronously. This is how your code flowed,

Declared obj -> Called FineOne (but callback is still not executed) -> Logged Obj (Still Blank) -> Callback of FineOne operation executed and populated some value in Obj

I hope it’s little more clear now. I would suggest you read these blogs:

Let me in the case of any clarification. Thanks!