Home > OS >  Mongoose increment, or set to maximum
Mongoose increment, or set to maximum

Time:04-24

I have a mongoose schema, with a cap/max of 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
}

Every 2 hours I have a cron job, where I want to increment the value by 5, however, if the value exceeds 20, it should simply be set to 20.

Ideally, the mongo query should have the following logic:

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

Is this kind of query possible in Mongoose?

CodePudding user response:

You can use $cond to perform the checking.

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
})

Here is the Mongo playground for your reference.

  • Related