"string?[]" - list of optionals vs optional list

I think, from my browsing of the docs and the realm-js tests it looks like the combination of ? and [] results in a list of optionals? E.g. ['a', null, 'b'].

Is there no way of specifying a property as an optional list? E.g the list could be entirely absent or, if present, it had mandatory values (e.g. null wouldn’t be allowed inside the list).

Hi @Liam_Jones, welcome to the community.

Could you please share a code sample?

Sure. Here’s a minimal one. We have 'things that can be scheduled daily or weekly. If they’re daily, you can specify multiple times you do it in a day. If they’re weekly you specify one time and the day of the week you do it on.

We could split the Daily/Weekly schedules to separate schemas but that then means we can’t link them from ScheduledThing directly and would have to query for/update them separately. Instead, we want a schema with enough optional properties that we can store both shapes inside it, only setting the relevant properties for the schedule type.

I’ve highlighted the thing that would ideally be either ‘undefined’ or an array of strings. The current setup isn’t the end of the world, it’s just we end up with empty arrays stored for dailyTimes on weekly schedules currently and it’d be nice if the whole list could be optional.

I hope that makes sense?

const ScheduledThing = {
    name: 'ScheduledThing',
    properties: {
        title: 'string',
        schedule: 'Schedule',
    },
}

const Schedule = {
    name: "Schedule",
    properties: {
        day: "string?",
        weeklyTime: "string?",
        dailyTimes: "string[]", // would like this to be string[]?
    },
}

const realm = await Realm.open({
    schema: [Schedule],
    deleteRealmIfMigrationNeeded: true,
})

const dailyScheduledThing = {
    name: 'Daily medication',
    schedule: {
        weeklyTime: undefined,
        day: undefined,
        dailyTimes: ['09:00', '10:00', '11:00'],
    },
}

const weeklyScheduledThing = {
    name: 'Food shopping',
    schedule: {
        day: "Wednesdays",
        weeklyTime: "16:30",
        dailyTimes: undefined,
    },
}

realm.write(() => {
    realm.create(Schedule.name, dailyScheduledThing)
    realm.create(Schedule.name, weeklyScheduledThing)
})

Lists cannot be optional in Realm. There’s no performance cost associated with them though, so whether they’re null or empty, it would be all the same. If you do need to differentiate between the null and empty case, you’ll need to use a separate property - e.g. scheduleType that can be either weekly or daily.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.