I can see there are a number of threads for this issue (or variations of it), but I am yet to find a definitive solution.
Here is a simple example:
I want to have a model that contains a predefined list of Cars (including primary key). A Person can then select any number of the cars (one-to-many). The cars should then be stored in a Car list type property in the Person model.
The issue is that if you have a primary key for each Car you quickly run into the error "
Attempting to create an object of type 'Car' with an existing primary key value
If you remove the primary key, you end up with a model containing a lot of redundancy, or at least it seems that way.
Some sample code:
import Realm from 'realm';
import { REALMFILEPATH } from '../constants'
class Car {}
Car.schema = {
name: 'Car',
primaryKey: 'id',
properties: {
id: 'int',
make: 'string',
model: 'string'
}
};
class Person {}
Person.schema = {
name: 'Person',
properties: {
name: {type: 'string'},
cars: {type: 'list', objectType: 'Car'}
}
};
let realm = new Realm({path: REALMFILEPATH, schema: [Car, Person]});
realm.write(() => {
let car1 = realm.create('Car', { id: 1, make: 'Honda', model: 'Civic' });
let car2 = realm.create('Car', { id: 2, make: 'Ford', model: 'Focus' });
let person1 = realm.create('Person', { name: 'Bob', cars: [{ id: 1, make: 'Honda', model: 'Civic' }] });
let person2 = realm.create('Person', { name: 'Simon', cars: [{ id: 2, make: 'Ford', model: 'Focus' }] });
let person3 = realm.create('Person', { name: 'Craig', cars: [{ id: 1, make: 'Honda', model: 'Civic' }, { id: 2, make: 'Ford', model: 'Focus' }] });
});
My question is, how do you add/update list types that contain primary keys?
If you pass true as the third argument to create then it will reuse/update existing objects with the same primary key if they exist, or create them if they don't. This argument should be passed down recursively when creating child objects so if you use this when creating a Person, existing cars should then be reused.
What is the third parameter's name? I was looking for it on your api doc website, but could not find it.
@fever324: Please file a new issue with your question as this one is quite old. However, feel free to reference this issue in the new one.
@fever324 there is document for that
https://realm.io/docs/javascript/latest/#realms
realm.write(() => {
// Create a book object
realm.create('Book', {id: 1, title: 'Recipes', price: 35});
// Update book with new price keyed off the id
realm.create('Book', {id: 1, price: 55}, true);
});
Most helpful comment
If you pass
trueas the third argument tocreatethen it will reuse/update existing objects with the same primary key if they exist, or create them if they don't. This argument should be passed down recursively when creating child objects so if you use this when creating aPerson, existing cars should then be reused.