0

I have this Profile model which has multiple fields including a profileBadges field which has this form:

 profileBadges: [
    {
      name: {
        type: String,
        required: true
      },
      description: {
        type: String,
        required: true
      }
    }
  ]

As you can see it's an array of objects. What I'm trying to do is to push an object into this array only if it doesn't exist already. I'm using mongoose and node. Basically I want to do this: Search the profileBadges array and check if the object exists. If it exists, do nothing. If it doesn't create a new entry. I read about $addToSet from mongoose and tried it but it keeps adding the record no matter what. What I have so far:

router.post(
  "/badge",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Profile.findOne({ user: req.user.id }).then(profile => {
      const newBadge = {
        name: req.body.name,
        description: req.body.description
      };
      profile
        .update({ $addToSet: { profileBadges: newBadge } }, { new: true })
        .then()
        .catch(err => res.status(404).json(err));
    });
  }
); 
Ovidiu G
  • 1,253
  • 5
  • 25
  • 47
  • woudn't `addToSet` itself add only if it's not in set? https://docs.mongodb.com/manual/reference/operator/update/addToSet/ - The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array. – kiddorails Jun 18 '18 at 12:00
  • Are your sub documents really identical? https://stackoverflow.com/questions/21011773/addtoset-works-like-push – dnickless Jun 18 '18 at 12:01
  • 1
    Following @dnickless answer, I found out that because of the _id field that mongo creates, the sub documents were not really identical, causing the duplication. For anyone facing this issue, there' a workaround this by making mongo not generate that id field. http://blog.open-tribute.org/2015/05/09/NodeJS-Mongoose-addToSet-duplicates-on-objects/ – Ovidiu G Jun 18 '18 at 12:10

0 Answers0