【发布时间】:2022-01-08 19:53:32
【问题描述】:
我有以下架构(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)会自动为我放入 bids 数组的每个投标项目创建 _id 字段。
我的问题是,如果我有一个出价的_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
【问题讨论】:
标签: javascript node.js mongodb mongoose