如果对象prop不在数组中,则更新
如果content.hash
不在数据库中,我想$push
variablescontent
$push
送到数据库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
这出现在谷歌,所以我想我会添加一个替代使用索引来实现独特的关键约束,如在子文档中的function,希望没关系。
我不太熟悉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'}, {...}, ...] }
关键是如果您的子文档密钥已经存在,确保更新不会返回文档进行更新(即查找部分)。