Search code examples
react-nativerealm

Realm and react Native Enable Updating Objects With Primary Keys for Nested Objects


How Can I Enable Update objects with Primary Key Globally

For the first instance I create the realm object and pass true for update with primary key, it works for root level object but the child objects throw an error on the second run

Error: Attempting to create an object of type 'Category' with an existing primary key value

Is there a way to set update via primary key globally

This is my structure

class Response extends Realm.Object {}
Response.schema = {
name: 'Response',
primaryKey: 'id',
properties: {
    id:'int',    // primary key
    categories: {type: 'list', objectType: 'CategoryList'},
  }
};
class CategoryList extends Realm.Object {}
CategoryList.schema = {
name: 'CategoryList',
properties: {
    category: {type: 'Category'},
  }
};
Category extends Realm.Object {}
Category.schema = {
primaryKey:'categoryId',
name: 'Category',
properties: {
    categoryId:'string',
    name:'string',
    itemsCount:'int',
    createdDate:'string'
  }
};

And this is how I persist to the db

    let Response = realm.objects('Response');
    let CategoryList = realm.objects('CategoryList');

        realm.write(()=>{
            realm.create('Response', {id:1,name: 'Response',categories: CategoryList},true);
            let Categories = Response[0].categories;

            for (let i=0;i<responseData.categories.length;i++){
                Categories.push(responseData.categories[i]);
            }
        });

Solution

  • My guess would be you are getting this error from this line:

    Categories.push(responseData.categories[i]);
    

    push implicitly tries to create a new category rather than updating/reusing existing categories. Try changing this to:

    Categories.push(realm.create('Catetory', responseData.categories[i], true));
    

    This will reuse existing categories if they exist, or create them if they don't.