javascript - Update if object prop doesn't exist in array -


i'd $push variable content database content if content.hash isn't in database. don't want store information again unnecessarily.

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

i have content object following params.

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

i don't want ever insert same csv array. i'd ensure there's 1 checking hash, if there's content object in array hash wouldn't upload or overwrite it.

here's got 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 data looks like, think it's close answer gave in thread. tldr; unique sub-documents.

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


this comes in google thought i'd add alternative using index achieve unique key constraint functionality in subdocuments, hope that's ok.

i'm not terribly familiar mongoose it's 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 ensure update not return document update (i.e. find part) if subdocument key exists.


Comments