0

When creating an object that has a primaryKey, does Realm provide a method to get / create next available unique value of a primary key? ( Auto-Increment )

const BookSchema = {
  name: 'Book',
  primaryKey: 'id',
  properties: {
    id:    'int',    // primary key
    title: 'string',
    price: 'float'
  }
};

If not what are approaches to insuring value of primaryKey is unique?

Or should I make primary key a uuid: { type: 'string' } ?

Using:

  • react native 0.38.1
    • Android
    • iOS
  • realm 0.15.0
Ed of the Mountain
  • 5,219
  • 4
  • 46
  • 54
  • I did not get your question please be more specific – Codesingh Jan 05 '17 at 19:13
  • 2
    If you're talking about auto-increment for primary key then it's not possible. Check this previous answer: http://stackoverflow.com/questions/40289738/why-realm-dont-support-auto-increment-primary-key/40290165#40290165 So my guess is you'd better use UUIDs. – Orlando Jan 05 '17 at 19:43
  • Yes auto-increment is what I meant. Thank-you! – Ed of the Mountain Jan 06 '17 at 00:31

1 Answers1

2

It's sad, but true.

Using uuid's for objects isn't as developer-friendly as a readable int. I recon it will impact performance as well. So if you don't want to, I think the best option would be to get the maximum id from the collection itself:

const getMaxId = (collection) => {
    const maxId = Math.max.apply(null,collection.map((item) => item.id));
    return maxId ? maxId : 1;
};
DerpyNerd
  • 4,743
  • 7
  • 41
  • 92