Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Increasing one field in a MongoDB collection with Mongoose

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;
    update = {$inc : {inStock : 1}};
    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.

Problem courtesy of: Masiar


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.

Solution courtesy of: danmactough


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Increasing one field in a MongoDB collection with Mongoose


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription