【发布时间】: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