iLoveUnicorns iLoveUnicorns - 1 year ago 129
Node.js Question

Mongoose cannot use simple methods from within self

I'm trying to use findAndUpdate from within the object class but it's not working.

Getting the following error

findByIdAndUpdate is not a function

The code


gameScheme.methods.makeNextRound = function() {

First thing, assign self (Before any lines)

var self = this;

Returning a Promise

return self.findByIdAndUpdate(
{ $push: { "rounds": { storyTitle: } } }

Cannot know how to get self properly from Mongoose since this method is defined before

// we need to create a model using it
let Game = mongoose.model('Game', gameScheme);

// make this available to our users in our Node applications
module.exports = Game;

On a side note, just using update doesn't work. The rounds do not get concatenated.

Also I think it's very unwise to use game.rouds[0] = "some round" or pushing directly and saving due to nodes async nature. (document miss match)

Answer Source

According to the Mongoose documentation for Schemas you define .methods and .statics on the schema. However, MongoDB methods are called directly on the model.

gameScheme.methods.makeNextRound = function () {
  return this.model("Game").findByIdAndUpdate(this._id,

Important: the actual interaction with the data happens with the Model that you obtain through mongoose.model or db.model. That's the object that you can instantiate or that you can call .find(), .findOne(), etc upon. Don't confuse schemas and actual models!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download