【问题标题】:How to conditionally include/exclude a field from a query in Mongoose?如何有条件地在 Mongoose 的查询中包含/排除字段?
【发布时间】: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[]
}

我需要一个返回bidsbids 的端点方法,但遵循以下规则:

如果请求出价的用户是拍卖的卖方,则包括 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


【解决方案1】:
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);   

}

【讨论】:

  • 我需要知道user.id === auction.seller 是否包含bids.bidderId,但我无法在查询整个拍卖文件之前检查该条件,我不希望
  • 这行得通,返回一个数组bids,其中包含所有bidderId,但我还需要包含bids.amountbids.date,这可能吗?
  • $cond: { if: { '$eq': ['$seller', user.id] }, then: '$bids', else: null }
  • else中,有没有办法返回$bids.date$bids.amount而不是null
  • 你可以试试这样吗:{"date":$bids.date,"amount": $bids.amount}
猜你喜欢
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多