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

180
Views
Cómo agregar un objeto a una matriz de objetos, usando addToSet o empujar operadores en mongodb

Tengo una serie de revisiones, quiero agregar una revisión usando addToSet que verificará si el usuario está presente en la matriz, entonces no queremos agregar ya que un usuario solo puede revisar una vez.

Mi esquema se ve así:

 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, }, }, ], });

Es posible que esté haciendo la consulta de forma incorrecta, pero no sé cómo agregar una reseña y verificar si el usuario actual no la ha revisado antes.

Aquí está la consulta donde agrego la revisión:

 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.", }); } });

Estoy pensando en verificar la identificación del vendedor y también verificar que el usuario actual no haya revisado, pero no funciona.

 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 );

RESPUESTA :

Pude resolver el problema, en caso de que otras personas tengan el mismo problema. Hice esto:

 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 );

Aquí está la documentación para el operador $nin: https://www.mongodb.com/docs/manual/reference/operator/query/nin/

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Está empujando el objeto de revisión dentro de un objeto. En su lugar haz esto:

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