Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing one field in a MongoDB collection with Mongoose

I'm trying to increment a value in a collection in my MongoDB database through Mongoose. This is the demo code shown on the Mongoose website:

var conditions = { name: 'borne' }
  , update = { $inc: { visits: 1 }}
  , options = { multi: true };

Model.update(conditions, update, options, callback)

And I have something like this:

var conditions = { "uniqueId" : itemId };
var update;
if(increase)
    update = {$inc : {inStock : 1}};
else
    update = {$dec : {inStock : 1}};
Item.update(conditions, update, {}, callback);

As you can see there is not much difference from the Mongoose's website code.

The problem is that when this piece of code is executed, I end up having in my collection one field called $dec (or $inc) which has an object as a field in the form {inStock : 1}. I just would like to increment the inStock entry of the collection. In the Schema I have:

var ItemToSell = new Schema({
    uniqueId : { type: Number, index: true }
  , name     : String 
  , type     : String
  , inStock  : Number
});

Can anyone point out what am I doing wrong? Thanks a lot.

like image 396
Masiar Avatar asked Feb 05 '12 16:02

Masiar


1 Answers

A) Make sure you're Mongoose is up-to-date. Older versions were very buggy on Model.update operations because Mongoose attempts to infer when you are merely passing a new object, in which case it turns your update object into a $set operation.

B) Try removing the empty {} from your function call. It is optional, and by passing an empty object rather than actual options, you may be confusing Mongoose into setting the { safe: false } option, which could also be causing your problem. I have not checked the source code to confirm that that could be the issue, but it's probably worth a try.

like image 76
danmactough Avatar answered Oct 11 '22 23:10

danmactough