Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

310
Views
How to add ObjectId only if the ObjectID is not present in the array in mongodb using mongoose?

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!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!