【问题标题】:Meteor mongodb $inc with update流星 mongodb $inc 更新
【发布时间】:2015-11-28 05:39:24
【问题描述】:

我有这个 mongo 集合和变量:

items:{
 type_one: 0,
 type_two: 0
}

var valueOne = 1;
var nameItem = type_one;

我尝试更新一个值,但不起作用。 我试过这个:

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 );

但没有一个有效,我收到此消息:

"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"}"

这是不兼容的问题吗?

【问题讨论】:

  • 你能展示你收藏的样本文件吗?

标签: mongodb meteor mongodb-query


【解决方案1】:

您需要使用方括号 [] 运算符动态构建查询。 “nameItem”也必须是一个字符串。

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

【讨论】:

    【解决方案2】:

    我能想到的唯一可能原因是您以String 的形式将数字插入集合中,或者您试图增加String 值。尝试在您的代码中使用parseInt(stringValue)

    【讨论】:

      猜你喜欢
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      相关资源
      最近更新 更多