Updating item in array with unique ID

房东的猫 提交于 2019-12-24 05:36:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!