gpt4 book ai didi

javascript - 如果数组中不存在对象 Prop 则更新

转载 作者:可可西里 更新时间:2023-11-01 09:15:11 25 4
gpt4 key购买 nike

如果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}
})
})

最佳答案

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

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


这出现在谷歌中,所以我想我会添加一个替代方法来使用索引来实现唯一的键约束,比如子文档中的功能,希望没问题。

我对 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'}, {...}, ...]
}

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

关于javascript - 如果数组中不存在对象 Prop 则更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31326305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com