繁体   English   中英

如何有条件地在 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[]
}

我需要一个返回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 数组中删除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);   

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM