使用唯一 ID 更新数组中的项目 [英] Updating item in array with unique ID
问题描述
我有这样的文档结构:
Content {
_id: "mongoId"
Title: "Test",
Age: "5",
Peers: [{uniquePeer: "1", Name: "Testy Test", lastModified: "Never"}, {uniquePeer: "2", Name: "Test Tester", lastModified: "Never"}]
}
所以 Peers
是一个具有唯一标识符的数组.如何更新数组中一组集合的 lastModified?根据 mongodb,我只能使用文档的唯一 ID 更新文档,但这是顶级的.我怎么能说在这个文档中用 uniquePeer
为 1 更新这组 Peers
中的这个 lastModified
字段?
So Peers
is an array that has a unique identifier. How can I update the lastModified of one of the sets in the array? According to mongodb I can only update a document using the document's unique ID, but that's at the top level. How can I say update this lastModified
field in this set of Peers
with a uniquePeer
of 1 in this document?
Content.update({"_id" : "mongoId", "Peers.uniquePeer" : "1"},{$set : {"Peers.$.lastModified" : "Now"}})
我仍然收到不允许.不受信任的代码只能通过 ID 更新文档."
I still get a "Not permitted. Untrusted code may only update documents by ID."
推荐答案
参见 docs 用于更新数组.您的代码应该类似于:
See the docs for updating an array. Your code should look something like:
服务器
Meteor.methods({
'content.update.lastModified': function(contentId, peerId) {
check(contentId, String);
check(peerId, String);
var selector = {_id : id, 'Peers.uniquePeer': peerId};
var modifier = {$set: {'Peers.$.lastModified': 'Now'}};
Content.update(selector, modifier);
}
})
客户
Meteor.call('content.update.lastModified', contentId, peerId);
请注意,这种操作需要在服务器定义的方法中进行,因为正如您发现的,您只能在客户端通过 id 更新文档.
Note that this kind of operation needs to take place in a server-defined method because, as you found out, you can only update docs by id on the client.
这篇关于使用唯一 ID 更新数组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!