I’m attempting to model the data in my database as “classes” in server-side JavaScript (Node).
For the moment, I’m simply using the traditional constructor pattern with prototype methods where appropriate and exposing the constructor function as the entire module.exports. The fact that this is server side is unimportant to the core of the question, but I figured I’d provide it as reference.
The problem area of code looks like this:
User.prototype.populate = function() {
var that = this;
db.collection("Users").findOne({email : that.email}, function(err, doc){
if(!err) {
that.firstName = doc.firstName;
that.lastName = doc.lastName;
that.password = doc.password;
}
console.log(that); //expected result
});
console.log(that); //maintains initial values
};
Whenever I call this function, changes to the object do not persist once the findOne() has completed. I realize that the scope of this changes to the global object with new function scopes, so I maintained its reference as that. If console.log(that) from within the anonymous function, the data shows up in the properties of it as expected. However, if I log that once the function has finished, it maintains the state it had at the beginning of the function.
What’s going on here and how I can I change instance variables as expected?
By this I assume you’re doing something like this…
If so, the
console.logwill run long before the asynchronous callback to.findOne()has been invoked.Any code that relies on the response to
findOneneeds to be invoked inside the callback.EDIT: Your update is a little different from my example above, but the reason is the same.
The entire reason for passing a callback to the
findOnemethod is that it performs an asynchronous activity. If it didn’t, there’s be no reason for the callback. You’d just place the inner code directly after the call tofindOne, as you did with theconsole.log().But because it’s asynchronous, the subsequent code doesn’t wait to execute. That’s why you’re getting the unpopulated object in the console.
If you add a label to each
console.log(), you’ll see that they execute out of order.So it becomes clear once you observer the order of the
console.logcalls that the empty one is happening before the one inside the callback.EDIT: You can also have your
.populate()method receive a callback that is invoked inside the.findOnecallback.