【发布时间】:2021-09-03 09:30:16
【问题描述】:
我有以下猫鼬模式:
export class Auction {
... Some other fields ...
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name, required: true, index: true })
seller!: string | User | Types.ObjectId
@Prop({
type: [{
bidderId: { type: Types.ObjectId, required: true, select: false },
amount: { type: Number, required: true },
date: { type: Date, required: true }
}],
select: false
})
bids?: Bid[]
}
我需要一个返回bids 的bids 的端点方法,但遵循以下规则:
如果请求出价的用户是拍卖的卖方,则包括 bids.bidderId,否则从投影中排除 bids.bidderId。
我该如何实现呢?假设我有这个方法:
async getBidsOfAuction(auctionId: string, user: UserDocument) {
// In case user.id === auction.seller, return all the fields including bids.bidderId
return await this.auctionModel.findOne({_id: auctionId, seller: user.id}).select('+bids +bids.bidderId')
// else, exclude bids.bidderId
return await this.auctionModel.findById(auctionId).select('+bids')
}
在查询拍卖之前我不知道是否auction.seller === user.id,并且我不想在查询之后手动(在JS中)从bids数组中删除bids.bidderId,因为它似乎是多余的。
有没有条件查询的方法如果拍卖的卖家等于用户id,则包含bids.bidderId,否则排除?
【问题讨论】:
-
无论如何都要检索
bids.bidderId,如果不是卖家,请在发送给客户之前将其删除。 -
这不会很好地扩展,想象一下我有一个包含 1000 个出价的数组(这在这个应用程序中很容易实现),这意味着我必须改变一个包含 1000 个的数组(对于每个请求)。如果有办法在数据库中做到这一点,那就更好了
标签: javascript node.js mongodb mongoose nestjs