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:
我正在尝试通过Mongoose增加MongoDB数据库中集合中的值。这是Mongoose网站上显示的演示代码:
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.
正如您所看到的,与Mongoose的网站代码没有太大区别。
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:
问题是,当执行这段代码时,我最终在我的集合中有一个名为$ dec(或$ inc)的字段,它有一个对象作为{inStock:1}形式的字段。我只想增加该系列的inStock条目。在Schema我有:
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.
谁能指出我做错了什么?非常感谢。
1 个解决方案
#1
3
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.
A)确保你的Mongoose是最新的。较旧的版本在Model.update操作上非常错误,因为Mongoose试图推断您何时只是传递一个新对象,在这种情况下,它将您的更新对象转换为$ set操作。
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.
B)尝试从函数调用中删除空{}。它是可选的,通过传递一个空对象而不是实际选项,您可能会混淆Mongoose设置{safe:false}选项,这也可能导致您的问题。我没有检查源代码以确认这可能是问题,但它可能值得一试。
#1
3
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.
A)确保你的Mongoose是最新的。较旧的版本在Model.update操作上非常错误,因为Mongoose试图推断您何时只是传递一个新对象,在这种情况下,它将您的更新对象转换为$ set操作。
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.
B)尝试从函数调用中删除空{}。它是可选的,通过传递一个空对象而不是实际选项,您可能会混淆Mongoose设置{safe:false}选项,这也可能导致您的问题。我没有检查源代码以确认这可能是问题,但它可能值得一试。