Home > Blockchain >  How to add ObjectId only if the ObjectID is not present in the array in mongodb using mongoose?
How to add ObjectId only if the ObjectID is not present in the array in mongodb using mongoose?

Time:05-09

so I have a schema where I want to add ObjectID to an array of id's in mongoose, I tried adding it unique, but did not work. Most likely because I need to iterate to check, but not sure how to do so in mongoose/mongodb. Can someone help me?

schema looks like this:

const favoriteSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    unique: true,
  },
  favoriteSellers: [
    //create array of object id, make sure they are unique for user not to add multiple sellers
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Seller",
      unique: true,
    },
  ],
});

and here is the code where I try to insert the Object ID only if it is not presennt:

router.put("/favorite", async (req, res) => {
  const seller_id = mongoose.Types.ObjectId(req.body.seller_id);
  Favorite.findOne({ user: req.user._id })
    .then(async function (result) {
      if (!result) {
        return res
          .status(404)
          .send({ error: "Could not find your list. Contact support team." });
      }
      result.favoriteSellers.push(seller_id);
      await result.save();
      res.send(result);
    })
    .catch((err) => {
      res.status(404).send({ error: "Could not add to favorites" });
    });
});

So what I am doing is getting the user id and adding new seller id to array, but I want to add condition if and only if the seller id is not pressent in the array of favoriteSellers. I can also do the logic in the front end before sending the seller id, but not sure if it will be better just to do it in the backend and not worry about it in the front end. Thank you!

CodePudding user response:

Looking at the Mongoose docs for adding subdocs to arrays, I think you should be able to use addToSet instead of push:

result.favoriteSellers.push(seller_id);

becomes

result.favoriteSellers.addToSet(seller_id);
  • Related