Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda