如何增加mongodb中的字段? [英] How to increment a field in mongodb?
问题描述
我具有以下Mongo DB文档结构:
I have the following Mongo DB document structure:
{
_id: channelId,
title: channelTitle,
pubDate: channelPubdate,
items:
[
{
title: newsTitle,
desc: newsDescription,
link: newsLink,
pubDate: Date,
clicks: 0
},
{/*One more*/},
{/*...*/}
]
}
我很难增加Collection中的"clicks"字段(更新嵌入在数组中的文档的字段).
I have troubles incrementing the "clicks" field in the Collection (updating the field of a document embedded in an array).
我在事件处理程序(客户端)中尝试过此操作:
I tried this in an event handler (client):
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]
But it gives an error: Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]
然后我通过服务器方法尝试了
I then tried via a server method:
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的正确要求是什么?
What would be a correct Mongo request for this action?
推荐答案
如错误所示,在客户端上,您只能使用简单的_id
选择器执行更新.我建议使用对您的代码稍作修改的方法:
As the error indicates, on the client you can only perform an update with a simple _id
selector. I'd recommend using a method with a slight modification to your code:
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}}
);
}
});
在这里,我们使用$
运算符来更新特定的嵌入式文档.有关更多详细信息,请参见文档.
Here we are using the $
operator to update the specific embedded document. See the docs for more details.
这篇关于如何增加mongodb中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!