[英]How to find document's array item by its "_id" field in MongoDB (Mongoose)?
I have the following schema (NestJS + Mongoose):我有以下架构(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[]
}
so basically every listing
document has an array of bids
.所以基本上每份
listing
文件都有一系列的bids
。
now I notice that automatically mongoDB (or mongoose) creates _id
field for every bid item I put into the bids
array.现在我注意到自动 mongoDB(或猫鼬)为我放入
bids
数组的每个投标项目创建_id
字段。
My question is, If I have a bid's _id
, how can I query it's item from the listing's bids array?我的问题是,如果我有一个出价的
_id
,我如何从列表的出价数组中查询它的项目? something like:就像是:
// 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
this.listingModel.findOne({ "bids._id": newBidId, {}, {}, (error, doc) =>
{
if (error) {
....
}
if (doc) {
....
} else {
...//'Not Found';
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.