【问题标题】:Updating item in array with unique ID使用唯一 ID 更新数组中的项目
【发布时间】:2015-08-03 20:27:07
【问题描述】:

我有一个这样的文档结构:

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 更新文档,但这是顶层。我怎么说更新这组Peers 中的lastModified 字段,并在本文档中将uniquePeer 设为1?

编辑:

Content.update({"_id" : "mongoId", "Peers.uniquePeer" : "1"},{$set : {"Peers.$.lastModified" : "Now"}})

我仍然收到“不允许。不受信任的代码只能按 ID 更新文档。”

【问题讨论】:

  • 我添加了一个更新,其中包含您所说的重复内容。我似乎无法让它为我工作。
  • 在我的代码中,uniquePeer 不是整数,它是一个有字母和数字的 guid,所以我必须在它周围加上引号。
  • 你是对的。谢谢。我已经更新了。

标签: mongodb meteor


【解决方案1】:

请参阅docs 以更新数组。您的代码应类似于:

服务器

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 更新文档。

【讨论】:

  • 字符串 'Now' 是否神奇地被 mongo 转换为 new Date()
  • 那很酷,但不,我只是在效仿他的榜样。
  • 这是我最初的想法——“mongo 是不是刚刚引入了一个新技巧?”所以约书亚,你可能想要new Date()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 2015-12-28
  • 2021-05-19
  • 2013-02-25
  • 2012-10-27
  • 2016-08-25
  • 1970-01-01
相关资源
最近更新 更多