Search code examples
updatesindexeddbdexie

With Dexie, how to remove a value from an array field for all objects in the table?


From this question I can find all objects in my table where a value occurs in a field that is an array. Now I need to delete that value from that field, for all objects in that table.

For example, suppose an events table, with objects:

{ people: ['John', 'Bob', 'Sue'] }
{ people: ['Harry', 'Sue', 'Jim'] }
{ people: ['John', 'Bob', 'Elaine'] }
{ people: ['Jim', 'Bob', 'Sue'] }

Suppose I want to delete 'Sue' from the people field for all objects.

How is this done with Dexie?


Solution

  • Adding the following code in an async function would do it:

    await db.events.where('people').equals('Sue').modify(x => {
      // This callback is run for every match.
      // Here you can modify the people property to remove Sue from it:
      x.people = x.people.filter(p => p !== 'Sue');
    });
    

    Note: Assume the schema is indexing 'people' with multiEntry index:

    const db = new Dexie("testdb");
    db.version(3).stores({
      events: 'id, *people'
    });
    

    References: