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

117
Views
¿Cómo encontrar el elemento de matriz del documento por su campo "_id" en MongoDB (Mongoose)?

Tengo el siguiente esquema (NestJS + Mongoose):

 @Schema({ timestamps: true }) export class Listing { @Prop({ type: [{ bidderId: { type: Types.ObjectId, required: true, select: false, ref: User.name, index: true }, amount: { type: Number, required: true }, date: { type: Date, required: true } }], select: false }) bids!: Bid[] }

así que básicamente cada documento de listing tiene una serie de bids .
ahora me doy cuenta de que automáticamente mongoDB (o mangosta) crea un campo _id para cada artículo de oferta que pongo en la matriz de bids .

Mi pregunta es: si tengo el _id de una oferta, ¿cómo puedo consultar su elemento de la matriz de ofertas de la lista? algo como:

 // Adding a new bid to the listing, and retrieving the updated listing const listingWithAddedBid = await this.listingModel.findByIdAndUpdate(listingId, { $push: { bids: { $each: [{ amount: bidInfo.amount, bidderId: new Types.ObjectId(user.id), date: new Date() }], $sort: { amount: -1 } } } }, { new: true }) // Getting the new bid's _id from the array (it will be at index 0 because we sort buy amount) const newBidId = listingWithAddedBid.bids[0]._id // here how can I query the entire bid item from the array with 'newBidId'? this won't work this.listingModel.findById(newBidId) // returns null
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

https://docs.mongodb.com/manual/tutorial/query-array-of-documents/ https://docs.mongodb.com/manual/indexes/#default-_id-index

 this.listingModel.findOne({ "bids._id": newBidId, {}, {}, (error, doc) => { if (error) { .... } if (doc) { .... } else { ...//'Not Found'; } });
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!