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));
});
}
);