如何有条件地 include/exclude 来自 Mongoose 查询的字段?
How to conditionally include/exclude a field from a query in Mongoose?
我有以下猫鼬模式:
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[]
}
我需要一个 returns 一个 Auction
的 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.bidderId
,因为它似乎多余。
有没有办法条件查询如果拍卖的卖家等于用户id,则包含bids.bidderId
,否则排除?
async getBidsOfAuction(auctionId: string, user: UserDocument) {
user.aggregate().match({_id: auctionId})
.project({
'seller': 1,
'type': 1,
'bids': {
$cond: {
if: {
'$eq': ['$seller', user.id]
},
then: '$bids.bidderId',
else: null
}
},
})
.exec(callback);
}
我有以下猫鼬模式:
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[]
}
我需要一个 returns 一个 Auction
的 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.bidderId
,因为它似乎多余。
有没有办法条件查询如果拍卖的卖家等于用户id,则包含bids.bidderId
,否则排除?
async getBidsOfAuction(auctionId: string, user: UserDocument) {
user.aggregate().match({_id: auctionId})
.project({
'seller': 1,
'type': 1,
'bids': {
$cond: {
if: {
'$eq': ['$seller', user.id]
},
then: '$bids.bidderId',
else: null
}
},
})
.exec(callback);
}