I'd like to $push
the variable content
into the database content
if the content.hash
isn't already in the database. I don't want to store information again unnecessarily.
return shops.updateAsync({
"user": user
}, {
"$push": {
"content": content
}
})
I have a content
object with the following params.
content = {
"type": "csv",
"name: "my-csv.csv",
"content": csvContent,
"date": new Date(),
"hash": hash.digest('hex')
}
I don't want to ever insert the same CSV into the array. I'd like to ensure that there's only one by checking the hash, if there's a content object in the array with the hash it wouldn't upload or overwrite it.
Here's what I got so far, it's 3 requests :(
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}
})
})
Not entirely sure what your data looks like, but I think it's very close to the answer I gave in another thread. TLDR; unique sub-documents.
https://stackoverflow.com/a/29102690/1058776
This comes up in google so I thought I'd add an alternative to using an index to achieve unique key constraint like functionality in subdocuments, hope that's OK.
I'm not terribly familiar with Mongoose so it's just a mongo console update:
var foo = { _id: 'some value' }; //Your new subdoc here
db.yourCollection.update(
{ '_id': 'your query here', 'myArray._id': { '$ne': foo._id } },
{ '$push': { myArray: { foo } })
With documents looking like:
{
_id: '...',
myArray: [{_id:'your schema here'}, {...}, ...]
}
The key being that you ensure update will not return a document to update (ie the find part) if your subdocument key already exists.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.