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 nullhttps://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'; } });