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

184
Visualizações
How to add an object to an array of object, using addToSet, or push operators in mongodb

I have an array of reviews, I want to add a review using addToSet that will check if user is present in the array, then we do not want to add since one user can only review once.

My schema looks like this:

const sellerSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    unique: true,
  },
  reviews: [
    {
      by: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        unique: true,
      },
      title: {
        type: String,
      },
      message: {
        type: String,
      },
      rating: Number,
      imagesUri: [{ String }],
      timestamp: {
        type: Date,
        default: Date.now,
      },
    },
  ],
});

I might be doing the query wrong, but can't figure out how to add a review and check if current user has not reviewed before.

Here is the query where I add the review:

router.post("/review/:_id/", async (req, res) => {
  try {
    const stylist_id = mongoose.Types.ObjectId(req.params._id);
    const review = {
        by: req.user._id,
        title: req.body.title,
        message: req.body.message,
        rating: parseFloat(req.body.rating),
    };
    if (req.body.imagesUri) {
      //if there is images, we need to set it up
      review.imagesUri = req.body.imagesUri;
    }
    await Seller.updateOne(
      { _id: seller_id },
      { $addToSet: { reviews: review } } //get the review that matches to the user_id
    );
    return res.status(200).send(true);
   }catch(err){
      res.status(502).send({
        error: "Error creating a review.",
     });
  }
});

I'm thinking of checking for seller's id and also check that no review is by current user, but it is not working.

const userID = req.user._id;
await Seller.updateOne(
      { _id: seller_id, reviews: { $elemMatch: { by: { $ne: { userID } } } } },
      { $addToSet: { reviews: review } } //get the review that matches to the user_id
    );

ANSWER:

I was able to solve the issue, in case other people have same issue. I did this:

await Seller.updateOne(
      {
        _id: seller_id, 
        "reviews.by": { $nin: [req.user.id] },
        //knowing req.user._id is a mongoose.Types.ObjectId. 
        //You can also use [id1, id2, ...] to the array to check for other id's
      },
      { $addToSet: { reviews: review } } //get the review that matches to the user_id
    );

Here is the documentation for $nin operator: https://www.mongodb.com/docs/manual/reference/operator/query/nin/

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are pushing the review object inside an object. Instead do this:

await Seller.updateOne(
  { _id: seller_id },
  { $addToSet: { reviews: review } }
);
about 4 years ago · Juan Pablo Isaza 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