问题
I've got a document structure like this:
Content {
_id: "mongoId"
Title: "Test",
Age: "5",
Peers: [{uniquePeer: "1", Name: "Testy Test", lastModified: "Never"}, {uniquePeer: "2", Name: "Test Tester", lastModified: "Never"}]
}
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?
Edit:
Content.update({"_id" : "mongoId", "Peers.uniquePeer" : "1"},{$set : {"Peers.$.lastModified" : "Now"}})
I still get a "Not permitted. Untrusted code may only update documents by ID."
回答1:
See the docs for updating an array. Your code should look something like:
server
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);
}
})
client
Meteor.call('content.update.lastModified', contentId, peerId);
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.
来源:https://stackoverflow.com/questions/31796164/updating-item-in-array-with-unique-id