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.


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.

链接地址: http://www.djcxy.com/p/10422.html

上一篇: Web应用程序中的ZeroMQ用法:前端如何与后端进行交互

下一篇: 用Mongoose增加MongoDB集合中的一个字段