4

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}
  })
})
4
  • Your question is very vague, could you provide more information? Commented Jul 9, 2015 at 19:14
  • 1
    @PBLC added some more context. Commented Jul 9, 2015 at 19:18
  • You wrote that you don't want to overwrite existing object if it's already present in content array, but in your code example you're overwriting it with new object. Which is the right behavior? Commented Jul 9, 2015 at 19:40
  • I want to overwrite / replace the existing one & I don't want duplicates. Sorry for the confusion. Commented Jul 9, 2015 at 20:46

1 Answer 1

1

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 (i.e. the find part) if your subdocument key already exists.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.