Skip to content Skip to sidebar Skip to footer

Perform $inc In Instance Method, Get Updated Document

I have an instance method in Mongoose where I need to perform Mongo's $inc operator on a field. My understanding is that since v3, Mongoose does not support $inc in any form other

Solution 1:

This would seem like the droids you are looking for:

usersSchema.methods.completePurchase = (item, incBalance, cb) ->
  model = @model(@constructor.modelName, @schema)
  model.findByIdAndUpdate @_id,
    $addToSet:
      purchases: item

    $inc:
      balance: incBalance
  , cb

Or in JavaScript:

usersSchema.methods.completePurchase = function(item, incBalance, cb) {

  var model = this.model(this.constructor.modelName, this.schema);
  return model.findByIdAndUpdate(this._id, {
    $addToSet: {
      purchases: item
    },
    $inc: {
      balance: incBalance
    }
  },
  cb);
};

And you would call as (JavaScript, sorry!):

user.completePurchase(item, incBalance function(err,doc) {
    // Something here
})

Or at least that works for me.


MyTest


var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/nodetest')

var childSchema = new Schema({ name: 'string' });

var parentSchema = new Schema({
  children: [childSchema]
});

parentSchema.methods.findMe = function(cb) {
  return this.model(this.constructor.modelName, this.schema)
    .findById(this._id, cb);
};

var Parent = mongoose.model('Parent', parentSchema);

var parent = new Parent( { children: [{ name: 'Bart' }] });

parent.save(function(err,doc) {

  console.log( "saved: " + doc );
  doc.findMe(function(err,doc2) {
    console.log( "found: " + doc2 );
  });

});

Post a Comment for "Perform $inc In Instance Method, Get Updated Document"