Realm-js: Auto increment id?

Created on 19 Dec 2016  路  8Comments  路  Source: realm/realm-js

Hello,

I'm liking Realm so far! I was wondering if auto incremented primary keys or ids would be supported something / is supported already. I didn't see anything in the docs about it.

T-Help

Most helpful comment

    Realm.open({ path: db, schema: [Qa] })
      .then(realm => {
        const results = realm.objects('Qa').sorted('id');
        const id = results.length > 0 ? results[results.length - 1].id + 1 : 1;
        realm.write(() => {
          realm.create('Qa', {...data, id});
        });
        return null;
      })
      .catch(error => {
        console.log(error);
      });

All 8 comments

Hi James,

sorry, we do not support it currently. You can see a discussion of the same request for Java here: https://github.com/realm/realm-java/issues/469

var ID = realm.objects('Student_Info').length + 1;

@rajscet
var ID = realm.objects('Student_Info').length + 1;
this code generates duplicate ID if some date removed from the table.

Lookup max value instead and add 1.

another solution is to use Guid instead int,
each time to create a new record generate new Guid.

hi, I resolve this issue with this steps :

  1. get the last Item in table :
    `_LastItem(){
    queryAllInventory().then((allInventory) => {
    if(allInventory.length==0){
    this.setState({ lastItemId:1 })
    }else{
    let lastItem= allInventory[allInventory.length-1]
    this.setState({ lastItemId: lastItem.id })
    }

    }).catch((error) => {
        this.setState({ error })
    })
    

    }`

  2. and i add 1 to last item :
    let insertInventoryObject = { **id: this.state.lastItemId+1,** raison: this.state.chosenRaison, date: this.state.chosenDate, statut: 'Ouvert' }

    Realm.open({ path: db, schema: [Qa] })
      .then(realm => {
        const results = realm.objects('Qa').sorted('id');
        const id = results.length > 0 ? results[results.length - 1].id + 1 : 1;
        realm.write(() => {
          realm.create('Qa', {...data, id});
        });
        return null;
      })
      .catch(error => {
        console.log(error);
      });

@rajscet
var ID = realm.objects('Student_Info').length + 1;
this code generates duplicate ID if some date removed from the table.

List ID 1, 2, 3
When delete ID 2
New Id = 3
Realm Creating failed.

Was this page helpful?
0 / 5 - 0 ratings