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

168
Views
Cómo recuperar un objeto de una matriz de objetos en mongodb dado un objectid

Tengo una serie de reseñas, quiero recuperar solo una reseña de una serie de objetos dentro de un esquema.

Aquí está mi esquema:

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

¿Cómo puedo obtener una sola revisión de la matriz si 'por' será req.user._id? Tengo el código anterior, pero no funciona para recuperar la revisión solo que satisface la consulta.

 try { const seller_id = mongoose.Types.ObjectId(req.params._id); const review = await Seller.findOne( { _id: seller_id }, { reviews: { $elemMatch: { by: req.user._id } } } //get the review that matches to the user_id ); res.status(200).send(review); } catch (err) { //sends the status code with error code message to the user res.status(502).send({ error: "Error retreiving review.", }); }

Esto recupera todo el documento del vendedor, pero solo quiero recuperar la revisión del objeto con el user_id dado === por: ObjectID

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

0

darle una oportunidad

 try { const seller_id = mongoose.Types.ObjectId(req.params._id); const review = await Seller.findOne( { _id: seller_id , "reviews.by": req.user._id}, { "reviews.$": 1 } ); res.status(200).send(review);

}

about 4 years ago · Juan Pablo Isaza Report

0

Intente convertir también el _id de usuario como ObjectId y unifique sus condiciones en un solo objeto:

 try { const seller_id = mongoose.Types.ObjectId(req.params._id); const user_id = mongoose.Types.ObjectId(req.user._id); const review = await Seller.findOne({ _id: seller_id, reviews: { $elemMatch: { by: user_id } }, }); res.status(200).send(review); } catch (err) { //sends the status code with error code message to the user res.status(502).send({ error: 'Error retreiving 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!