Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在mongodb中增加字段?_Mongodb_Meteor - Fatal编程技术网

如何在mongodb中增加字段?

如何在mongodb中增加字段?,mongodb,meteor,Mongodb,Meteor,我有以下Mongo DB文档结构: { _id: channelId, title: channelTitle, pubDate: channelPubdate, items: [ { title: newsTitle, desc: newsDescription, link: newsLink, pubDate: Date, clicks: 0 }, {/*One more*/}

我有以下Mongo DB文档结构:

{
  _id: channelId, 
  title: channelTitle,
  pubDate: channelPubdate, 
  items: 
  [
    {
      title: newsTitle,
      desc: newsDescription, 
      link: newsLink, 
      pubDate: Date, 
      clicks: 0
    },
    {/*One more*/},
    {/*...*/}
  ] 
}
我在增加集合中的“clicks”字段(更新数组中嵌入的文档的字段)时遇到问题

我在事件处理程序(客户端)中尝试了此操作:

但它给出了一个错误:
uncaughterror:不允许。不受信任的代码只能按ID更新文档。[403]

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

Meteor.methods({
    incClicks: function(id, news) 
    {
      News.update({ _id : id, "items.link" : news.link }, 
        { $inc : { "items.clicks": 1 } }
      );
    }
});
然而,另一个异常:
调用方法“incClicks”时异常MongoError:无法使用字符串字段名追加到数组:clicks


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

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

Meteor.methods({
incClicks:函数(id、新闻){
检查(id、字符串);
检查(news,Match.ObjectIncluding({link:String}));
最新消息(
{{u id:id,'items.link':news.link},
{$inc:{'items.$.clicks':1}
);
}
});

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

问题在于
是一个数组。它可能包含多个项目-每个项目都有自己的
点击次数。你想增加哪一个?不是全部。仅调用事件处理程序所在的元素。我在站点上显示项目中的对象。用户可以点击一些元素(项目中的对象),然后我需要计算它点击这个元素的次数并更新数据库。换句话说,增加mongo中相应对象的“clicks”字段。
Meteor.methods({
    incClicks: function(id, news) 
    {
      News.update({ _id : id, "items.link" : news.link }, 
        { $inc : { "items.clicks": 1 } }
      );
    }
});