Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

308
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda