猫鼬增量,或设置为最大值

Mongoose increment, or set to maximum

我有一个 mongoose 模式,cap/max 为 20

//The maximum amount of users that a user can receive
export const LIKE_LIMIT_CAP = 20
//The amount of likes given every two hours to the user
export const LIKE_LIMIT_INCREASE = 5

@Schema()
export class LikeLimit extends Document {
  @Prop({ required: true })
  userId: number

  @Prop({ required: true, default: 0, max: LIKE_LIMIT_CAP, min: 0 })
  likeLimit: number

  @Prop({ default: null })
  lastLikedDate: Date
}

每 2 小时我有一个 cron 作业,我想将值增加 5,但是,如果值超过 20,则应该简单地设置为 20。

理想情况下,mongo 查询应具有以下逻辑:

if(likeLimit >= LIKE_LIMIT_CAP - LIKE_LIMIT_INCREASE){
   likeLimit = LIKE_LIMIT_CAP
}else{
   likeLimit = likeLimit + LIKE_LIMIT_INCREASE
}

这种查询在 Mongoose 中可行吗?

您可以使用 $cond 来执行检查。

db.collection.update({
  userId: <userId>
},
[
  {
    "$addFields": {
      "likeLimit": {
        "$cond": {
          "if": {
            $gt: [
              {
                "$add": [
                  "$likeLimit",
                  <LIKE_LIMIT_INCREASE>
                ]
              },
              <LIKE_LIMIT_CAP>
            ]
          },
          "then": <LIKE_LIMIT_CAP>,
          "else": {
            "$add": [
              "$likeLimit",
              <LIKE_LIMIT_INCREASE>
            ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

这里是Mongo playground供您参考。