pricop
pricop

Reputation: 43

How to check if a sub-document exist before pushing to array

I have tried searching but found non that fits my query, I have a JSON output like this that exist in database

{ _id: 59c255f1f3e91433b4d4b58e,
  name: 'example name';,
  __v: 52,
  contacts: 
   [ { contactId: '59c255f1f3e91433b4d4b58e', //duplicated
        _id: 59c2a9f0471ffb202c3771d2,
       added: 2017-09-20T17:48:32.328Z },
      { contactId: '59c255f1f3e91433b4d4b58e', //duplicated
       _id: 59c2ac524fc91235a0d89195,
       added: 2017-09-20T17:58:42.956Z }
      { contactId: '59c255f1f3e91433b4234eff',
       _id: 59c2ac524fc91235a0d89195,
       added: 2017-09-20T17:58:42.956Z }
       ],
}

How can I check if all contacts.contactId exist with this contactId "59c255f1f3e91433b4d4b58e" before trying to push another contactId, it keeps appending to array, I need to make sure that only one contactId with "59c255f1f3e91433b4d4b58e" get pushed to the contacts array, no matter what.

I don't have any clue on how to do that, I have tried:

User.findOne({_id: req.user.id}, function(err, newadd) { 
if(!newadd === req.req.params.to){ // also tried "indexOf" ^^ "lastIndexOf"
newadd.contacts.push({
    contactId:req.params.to
    })
newadd.save()
}else{
res.end('already exist try again')
}
  })

(I am using mongoose) I will really appreciate any help :(

Upvotes: 1

Views: 1210

Answers (2)

Vignesh
Vignesh

Reputation: 1222

You may use $addToSet this will not allow duplicates in resulting array for more info checkout $addToSet

the above was for mongoose and to answer your approch

 User.findOne({_id: req.user.id}, function(err, newadd) { 
     if(!newadd._id === req.params.to){
         newadd.contacts.push({
             contactId:req.params.to
         })
         newadd.save()
     }else{
         res.end('already exist try again')
     }
  })

Upvotes: 1

Adriyana Putra Pratama
Adriyana Putra Pratama

Reputation: 176

hmmmm mybe just like this

User.findOne({_id: req.user.id}, function(err, newadd) { 
var test = newadd.contacts.filter(function(result){
   if ((result.contactId === req. !.....) === true){
       console.log()
   }else{
       console.log()
   }
})

Upvotes: 0

Related Questions