realm / realm-js

Realm is a mobile database: an alternative to SQLite & key-value stores
https://realm.io
Apache License 2.0
5.81k stars 577 forks source link

Upsert embedded objects when updating parent with modified #6932

Open tehvgg opened 1 week ago

tehvgg commented 1 week ago

Problem

I have a primary object that contains an embedded object. I receive updates from the server and would like to simply call realm.create(MyObj, data, Realm.UpdateMode.Modified).

However, these payloads are large and while we receive them in full during initialization, updates often contain partials of the embedded objects (I do not have control over the server data or how it is provided).

Currently, when upserting the parent, the embedded children are re-created rather than themselves being upserted.

I'm wondering if there's some way for me to stick with a 1-line upsert to update my db, or if I'm going to have to write a bunch of manual updates for the embedded objects.

// objects
class MyObj extends Realm.Object<MyObj> {
  id: string;
  emb: MyEmb;

  static schema: Realm.ObjectSchema = {
    name: 'MyObj',
    primaryKey: 'id',
    properties: {
      id: 'string',
      emb: 'MyEmb',
    },
  }
}

class MyEmb extends Realm.Object<MyEmb> {
  str: string;
  boo: boolean;

  static schema: Realm.ObjectSchema = {
    name: 'MyEmb',
    embedded: true,
    properties: {
      str: 'string',
      boo: 'bool',
    },
  }
}

// init
realm.create(
  Primary,
  {
    id: 'id-1',
    emb: {
      str: 'a',
      boo: false,
    },
  },
  Realm.UpdateMode.Modified,
);

// update fail, MyEmb missing 'boo'
realm.create(
  Primary,
  {
    id: 'some-guid-1234',
    emb: {
      str: 'A',
    },
  },
  Realm.UpdateMode.Modified,
);

Solution

No response

Alternatives

  1. Manually handle updates in the form of obj.emb.str = data.emb.str, however given the scale of the data (many many many primary objects that contain embedded objects), I'd really prefer just having a one line upsert if possible.
  2. Convert embedded objects to primary, however many of these nested objects don't have properties that could be used as a primary key.

How important is this improvement for you?

Would be a major improvement

Feature would mainly be used with

Local Database only

sync-by-unito[bot] commented 1 week ago

➤ PM Bot commented:

Jira ticket: RJS-2920