0

I am trying to do something like this;

var fieldName = 'name';
if ((await db.friends.where({ ${fieldName}: 'Josephine'}).count()) === 0) {
        const id = await db.friends.add({name: "Josephine", age: 21});
        alert (`Addded friend with id ${id}`);
    }

Is the any way to do this thing in Javascript? Thanks

R0bertinski
  • 366
  • 2
  • 10

1 Answers1

2

Yes, but you have to use []:

var fieldName = 'name';
if ((await db.friends.where({ [fieldName]: 'Josephine'}).count()) === 0) {
    const id = await db.friends.add({name: "Josephine", age: 21});
    alert (`Addded friend with id ${id}`);
}
Marian Theisen
  • 5,930
  • 26
  • 38
  • (I dont know the use case and background, BUT be aware of SQL injection possibilities if you do stuff like this. If you can, use an allow-list for the fieldNames - if your ORM does not prevent this automatically) – Marian Theisen Mar 25 '21 at 06:46