I'm using Node here and the following function is being used as a controller action. I'm using Mongoose to access a model and within the scope of the Game.findById(), I cannot access any of the variables above it, namely this.player and this.gameId.
Does anyone know what I doing wrong? Note that I want to access the variables where the console.log() statement is, but I can't access it. this.player returns undefined. Thanks in advance for your help.
exports.cleanup = function(req, res) {
this.player = req.body;
this.gameId = req.url.split('/')[2];
debugger;
Game.findById(this.gameId, function(err, game) {
if (err) return err;
console.log(this.player);
});
};
this
is referring to different things inside the two functions, each of which has its own scope and its own this
(although this
might be undefined in some circumstances, see a couple of references below).
What you'll want is something like the following - note the self
variable.
exports.cleanup = function(req, res) {
this.player = req.body;
this.gameId = req.url.split('/')[2];
var self=this;
debugger;
Game.findById(this.gameId, function(err, game) {
if (err) return err;
console.log(self.player);
});
};
A couple of resources which may be of help understanding this
:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.