This question has already been answered:

I switched to mongoDB and it turned out that I need to write the found data to this.buyer object, but this does not work. How to do it correctly and how to call after writing a function?

 PlayerTracker.prototype.updateBuyers = function() { if (!db) return; this.buyer = {}; // work this.updateData(); // work db.collection("buyers").findOne({uuid: this._uuid}, function(err, b) { if (err) throw err if (!b) return; this.buyer = b; // dont work this.updateData(); // dont work }); } 

Reported as a duplicate by participants Stepan Kasyanenko , Grundy javascript Mar 29 at 8:11 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • No need to make the code picture. We do not have to rewrite for you, for the sake of the test. - And

1 answer 1

The easiest way to use the arrow function is to use the context of ( this ) their environment:

 PlayerTracker.prototype.updateBuyers = function () { // ... db.collection("buyers").findOne({ uuid: this._uuid }, (err, b) => { if (err) throw err; if (!b) return; this.buyer = b; this.updateData(); }); } 

ps: The object of the class instance (the prototype of which you complement) is not global ... at least it is of the second level. The global object in Node is global .

  • Thank! I didn’t even think that the arrow functions would work in it) - Yegor Belov
  • @EgorBelov, the switch functions are actually the same functional expressions, just without its this - therefore, wherever the "ordinary" FWs work, the arrows will also work (of course, if the user agent supports them). - yar85