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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With