【问题标题】:How to increment a field in mongodb?如何在mongodb中增加一个字段?
【发布时间】:2015-02-26 17:32:49
【问题描述】:

我有以下 Mongo DB 文档结构:

{
  _id: channelId, 
  title: channelTitle,
  pubDate: channelPubdate, 
  items: 
  [
    {
      title: newsTitle,
      desc: newsDescription, 
      link: newsLink, 
      pubDate: Date, 
      clicks: 0
    },
    {/*One more*/},
    {/*...*/}
  ] 
}

我在增加集合中的“clicks”字段时遇到了麻烦(更新嵌入在数组中的文档的字段)。

我在事件处理程序(客户端)中尝试过这个:

News.update({ _id : Session.get("channelId"), "items.link" : this.link },
  { $inc: { "items.clicks": 1 } }
);

但它给出了一个错误:Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]

然后我尝试通过服务器方法:

Meteor.methods({
    incClicks: function(id, news) 
    {
      News.update({ _id : id, "items.link" : news.link }, 
        { $inc : { "items.clicks": 1 } }
      );
    }
});

然而,另一个例外:Exception while invoking method 'incClicks' MongoError: can't append to array using string field name: clicks

对此操作的正确 Mongo 请求是什么?

【问题讨论】:

  • 问题是items是一个数组。它可能包含多个项目 - 每个项目都有自己的 clicks 计数。你想增加哪一个?
  • 不是全部。仅调用事件处理程序的元素。我展示了现场物品中的物品。并且用户可以点击某个元素(项目中的对象),之后我需要计算它对该元素的点击次数并更新数据库。换句话说,在 mongo 中增加相应对象的“clicks”-filed。

标签: mongodb meteor


【解决方案1】:

如错误所示,在客户端上您只能使用简单的_id 选择器执行更新。我建议使用对您的代码稍作修改的方法:

Meteor.methods({
  incClicks: function(id, news) {
    check(id, String);
    check(news, Match.ObjectIncluding({link: String}));

    News.update(
      {_id: id, 'items.link': news.link},
      {$inc: {'items.$.clicks': 1}}
    );
  }
});

这里我们使用$ 操作符来更新特定的嵌入文档。有关详细信息,请参阅docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 2021-07-03
    相关资源
    最近更新 更多