Home > other >  MongoDB $inc field
MongoDB $inc field

Time:07-22

I'm trying to write a function that takes a record id, an action, i.e. inc or dec, and a field name as a string to be incremented (it can be 'likes', 'subs', whatever).

And I can't figure out how I can replace the likes in this line $inc: { likes: 1 } with the field prop passed to function. I tried $inc: { field: 1 }, but field prop doesn't exist on schema.

  async update(id: string, action: string, field: string) {
    switch (action) {
      case 'inc':
        await this.userModel.findByIdAndUpdate(id, {
          $inc: { likes: 1 },
        });
      case 'dec':
        await this.userModel.findByIdAndUpdate(id, {
          $inc: { likes: -1 },
        });
    }
  }

CodePudding user response:

you can use it like this

$inc: { [field]: string }

Note: check field value (using if/else) before performing operation because if someone passes "password" as field value and you have field named "password" in that record either it will throw an error or increments that field which you don't to happen.

For types, use something like this

field: keyof Pick<UserSchema, 'likes' | 'subs' | 'whatever' >
  • Related