如何增加mongodb中的字段?

dvp*_*lut 4 mongodb meteor

我有以下Mongo DB文档结构:

{
  _id: channelId, 
  title: channelTitle,
  pubDate: channelPubdate, 
  items: 
  [
    {
      title: newsTitle,
      desc: newsDescription, 
      link: newsLink, 
      pubDate: Date, 
      clicks: 0
    },
    {/*One more*/},
    {/*...*/}
  ] 
}
Run Code Online (Sandbox Code Playgroud)

我有麻烦增加Collection中的"clicks"字段(更新嵌入在数组中的文档的字段).

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

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

但它给出了一个错误: 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 } }
      );
    }
});
Run Code Online (Sandbox Code Playgroud)

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

什么是正确的Mongo请求这个动作?

Dav*_*don 7

如错误所示,在客户端上,您只能使用简单的_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}}
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

这里我们使用$运算符来更新特定的嵌入式文档.有关更多详细信息,请参阅文档.