【问题标题】:Update if object prop doesn't exist in array如果数组中不存在对象道具,则更新
【发布时间】:2015-07-09 19:13:41
【问题描述】:

如果content.hash 尚未在数据库中,我想将$push 变量content 放入数据库content。我不想不必要地再次存储信息。

return shops.updateAsync({
  "user": user
}, {
  "$push": {
    "content": content
  }
})

我有一个带有以下参数的 content 对象。

content = {
  "type": "csv",
  "name: "my-csv.csv",
  "content": csvContent,
  "date": new Date(),
  "hash": hash.digest('hex')
}

我不想将相同的 CSV 插入到数组中。我想通过检查哈希来确保只有一个,如果数组中有一个带有哈希的内容对象,它不会上传或覆盖它。

这是我目前得到的,这是 3 个请求:(

return users.findOneAsync({
  "user": user,
  "content.hash": content.hash,
}).then(function(exists){
  if(!exists) return false
  return users.updateAsync({
    "user": user
  }, {
    "$pull": { "content": { "hash": content.hash } },
  })
}
}).then(function(){
  return users.updateAsync({
    "user": user,
  }, {
    "$push": {"content": content}
  })
})

【问题讨论】:

  • 你的问题很模糊,能否提供更多信息?
  • @PBLC 添加了更多上下文。
  • 您写道,如果现有对象已经存在于 content 数组中,您不想覆盖它,但在您的代码示例中,您正在用新对象覆盖它。哪种行为是正确的?
  • 我想覆盖/替换现有的并且我不想重复。很抱歉造成混乱。

标签: javascript node.js mongodb


【解决方案1】:

不完全确定您的数据是什么样的,但我认为它与我在另一个线程中给出的答案非常接近。 TLDR;独特的子文档。

https://stackoverflow.com/a/29102690/1058776


这出现在 google,所以我想添加一个替代方法来使用索引来实现子文档中的唯一键约束,例如功能,希望没关系。

我对 Mongoose 不是很熟悉,所以它只是一个 mongo 控制台更新:

var foo = { _id: 'some value' }; //Your new subdoc here

db.yourCollection.update(
{ '_id': 'your query here', 'myArray._id': { '$ne': foo._id } },
{ '$push': { myArray: { foo } })

文档看起来像:

{
  _id: '...',
  myArray: [{_id:'your schema here'}, {...}, ...]
}

如果您的子文档键已存在,则确保 update 不会返回要更新的文档(即查找部分)的关键。

【讨论】:

    猜你喜欢
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    相关资源
    最近更新 更多