Meteor mongodb $inc with update

冷暖自知 提交于 2019-12-20 06:36:51

问题


I have this mongo collection and vars:

items:{
 type_one: 0,
 type_two: 0
}

var valueOne = 1;
var nameItem = type_one;

I try to update a value, but not work. I tried this:

Collection.update({createdBy: user_id}, {$inc: { items.$.nameItem: valueOne}} );
Collection.update({createdBy: user_id}, {$inc: { "items.$.nameItem": valueOne}} );
Collection.update({createdBy: user_id}, {$inc: { "items."+nameItem: valueOne}} );
Collection.update({createdBy: user_id}, {$inc: { "items."+nameItem: 1}} );

var object = { $inc: { "items."+nameItem: valueOne} };
Collection.update({createdBy: user_id}, object );
var object = { $inc: { items.$.nameItem: valueOne} };
Collection.update({createdBy: user_id}, object );

But none works and I get this message:

"errorClass {error: 409, reason: "MinimongoError: Cannot apply $inc modifier to non-number", details: undefined, message: "MinimongoError: Cannot apply $inc modifier to non-number [409]", errorType: "Meteor.Error"}"

It's a issue o incompatibility?


回答1:


You need to build your query dynamically using the bracket [] operator. Also "nameItem" must be a string.

var valueOne = 1;
var nameItem = 'type_one';
var inc = {};
inc[ 'items.' + nameItem ] = valueOne;
Collection.update({ createdBy: user_id }, { '$inc': inc } )



回答2:


The only possible reasons I can come up with this that either you inserted number into collection in the form of String or you're trying to increment with String value. Try using parseInt(stringValue) in your code.



来源:https://stackoverflow.com/questions/33968094/meteor-mongodb-inc-with-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!