我有以下架構(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[]
}
所以基本上每個listing檔案都有一個bids.
現在我注意到 mongoDB(或 mongoose)會自動_id為我放入bids陣列的每個投標專案創建欄位。
我的問題是,如果我有一個出價_id,我如何從串列的出價陣列中查詢它的專案?就像是:
// 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
uj5u.com熱心網友回復:
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';
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408428.html
標籤:
