Mongoose: access model.update in schema method?

Created on 28 Nov 2011  路  6Comments  路  Source: Automattic/mongoose

schema.methods.mySave = function(){
// dostuffhere
this.save()
}
schema.methods.myRemove = function(){
// dostuffhere
this.remove()
}
schema.methods.myUpdate = function(){
// dostuffhere
this.update()
}

first 2 work, but i can't access update within the schema method

Most helpful comment

schema.methods.inc = function (howMany, callback) {
  var query = { _id: this._id };
  var update = { $inc: { count: howMany }};
  this.constructor.update(query, update, callback);

  // in v3 
  // this.update(update, callback)
}

All 6 comments

Also interested in this. Can anyone confirm?

this.save() handles updates transparently. otherwise you'd use Model.update for that.

@aheckmann - can you elaborate on how you would use Model.update in this context? (instance method). In particular I'm interested in having the model instance increment one of it's fields.

schema.methods.inc = function (howMany, callback) {
  var query = { _id: this._id };
  var update = { $inc: { count: howMany }};
  this.constructor.update(query, update, callback);

  // in v3 
  // this.update(update, callback)
}

Doesn't seem to work in 5.1.1:

TypeError: this.constructor.update is not a function

returned by:

UserSchema.methods = {
...
    addPoints: async () => {
        ...
        await this.constructor.update({ _id: this._id }, {
                $inc: incObj
            }, { new: true }).exec();
        ...
    }
}

@kerberjg there is no 5.1.1 release at the time of this writing. Also, get rid of the arrow function for addPoints and it should work because of how arrow functions handle this

UserSchema.methods = {
...
    addPoints: async function() {
        ...
        await this.constructor.update({ _id: this._id }, {
                $inc: incObj
            }, { new: true }).exec();
        ...
    }
}
Was this page helpful?
0 / 5 - 0 ratings