Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB $inc field

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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' >
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading