Sunner
Sunner

Reputation: 25

IndexedDB/Dexie MultiEntry index on nested properties within array

I'm using Dexie in a web application to store application data. I'm trying to create a MultiEntry index for a property nested inside an array, but I'm not sure if something like this is possible or not.

I know I can create an index like this with Dexie:

class ExampleDatabase extends Database {
    constructor() {
        this.version(1).stores({
            data: 'id, *categories'
        });
    }
}

if my data looks like this:

[
    { id: 1, name: "Object 1", categories: ["asdf", "test"] },
    { id: 2, name: "Object 2", categories: ["qwer", "whatever"] },
]

But what if my data looks more like this:

[
    {
        id: 1,
        name: "Object 1",
        categories: [
            { id: 1, name: "asdf" },
            { id: 2, name: "test" }
        ]
    },
    {
        id: 2,
        name: "Object 2",
        categories: [
            { id: 3, name: "qwer" },
            { id: 4, name: "whatever" }
        ]
    },
]

Is there any way I could set a MultiEntry index on the name here if it's inside of an object like this? Something like *categories[].name? Or is this simply not possible to do with this data structure?

Upvotes: 0

Views: 21

Answers (1)

David Fahlander
David Fahlander

Reputation: 5691

IndexedDB only supports multientry indexing of arrays with plain indexable values (strings, numbers, ArrayBuffers, or arrays - not objects).

One way to work around this is to store the sub properties redundantly in an array at the root level and index that:

{
    id: 1,
    name: "Object 1",
    categories: [
        { id: 1, name: "asdf" },
        { id: 2, name: "test" }
    ],
    categoryNames: ["asfd", "test"] // copies of the "name" prop of categories array
}


class ExampleDatabase extends Database {
    constructor() {
        this.version(1).stores({
            data: 'id, *categoryNames'
        });
    }
}

Upvotes: 2

Related Questions