0

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);
  });
}; 
user1717344
  • 133
  • 1
  • 8

1 Answers1

0

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:

Community
  • 1
  • 1
barry-johnson
  • 3,204
  • 1
  • 17
  • 19