Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store Array of Objects in realm-js?

    import Realm from 'realm';

    class Cities extends Realm.Object {}
    class Users extends Realm.Object {}

    Cities.schema = {
      name: 'Cities',
      properties: {
        'name': {
          type: 'string'
        },
        'pincode': {
          type: 'int'
        }
      }
    };

    Users.schema = {
      name: 'Users',
      primaryKey: 'id',
      properties: {
        'id': 'string',
        'name': {
          type: 'string'
        },
        'city': {
          type: 'list',
          objectType: 'Cities'
        }
      }
    };

    const schemaList = [Users, Cities];

    const realmInstance = new Realm({schema: schemaList});

    export default realmInstance;

// pushing a cityObj (that is already present in 'Cities') for a existing User:

onPress={() => this.addCity({name: 'Delhi', pincode: 110004})}

addCity = (cityObj) => {
    realm.write(() => {
      let user = realm.create('Users', {
        'id': 'someUniqueID'
      }, true);
      user.city.push(cityObj);
    });

    let cities = realm.objects('Cities');
    console.log('cities.length', cities.length);
  }

though, trying to update a record in 'Users', The write transaction is writing a new record in Cities table as well creating duplicates. Why so?

like image 396
Anshul Masne Avatar asked Jan 29 '23 01:01

Anshul Masne


1 Answers

Adding to a list will in general create a new object. But you can add a primary key to Cities, create/update the object first and finally push it to the list. Something like:

const Realm = require('realm');

const CitiesSchema = {
    name: 'Cities',
    primaryKey: 'pincode',
    properties: {
        'name': {
            type: 'string'
        },
        'pincode': {
            type: 'int'
        }
    }
};

const UsersSchema = {
    name: 'Users',
    primaryKey: 'id',
    properties: {
        'id': 'string',
        'name': {
            type: 'string'
        },
        'city': {
            type: 'list',
            objectType: 'Cities'
        }
    }
};

const schemaList = [UsersSchema, CitiesSchema];
const realm = new Realm({schema: schemaList});


addCity = (cityObj) => {
    realm.write(() => {
        let city = realm.create('Cities', cityObj, true);
        let user = realm.create('Users', {
            id: 'someUniqueID',
            name: 'Foo Bar'
        }, true);
        user.city.push(city);
    });

    let cities = realm.objects('Cities');
    console.log('cities.length', cities.length);
}

addCity({name: 'Delhi', pincode: 110004});
addCity({name: 'Delhi', pincode: 110004});
like image 164
geisshirt Avatar answered Feb 03 '23 07:02

geisshirt