ConstraintError: Key already exists in the object store
Asked Answered
M

1

7

I am working with React 16.3.2, Redux 4 and Dexie 2.0.3.

when I am going to store data second time it throws this error message.

Error: ConstraintError: Key already exists in the object store.

   return dispatch => {
        db.table
        .add(data)
        .then (function(id){
            console.log(id)
        })
        .catch (function (error) {
            console.log("Error: " + error);
        });
    }

My Db schema:

   const db = new Dexie('ReactReduxDexieJsCRUD');
  db.version(1).stores({table:'++id,name,age,bloodGroup,donateBefore,weight' });

The first time it stores date well but after it gives the error.

Macilroy answered 17/5, 2018 at 18:25 Comment(8)
Try put(data) instead of add(data).Silverfish
I didn't worked with Dexie, but similar problem on MySql can be solved with "ON DUPLICATE KEY UPDATE". If you want on second call to add new data as new record, you need to set table key to be autoincrement, or to specify new key manually as second parameter to add call. If you want to add data or update data if exist, try [dexie.org/docs/Table/Table.put()](put) instead of add.Genic
Lovely comment #Oblosys & #stolex but it creates another issue it doesn't change the ID and it works like #update in databaseMacilroy
works as expected, but you dont want an update, so what do you actually want to happen when a duplicate key is used?Unaware
@smith I don't want to use the duplicate key. and why it gives me error duplicate key . i am submitted my from second time with new value so it should be store new data with new ID ?Macilroy
2nd time, sublimating a a duplicate key, what do you want to happen?Unaware
2nd,3rd..... it will store data in indexDB local database. continuously data inserted in the database.Macilroy
@smith please take a look my code Github project linkMacilroy
H
8

How does your schema look like? (the part db.version(x).stores({...}) ?

The most common is to have inbound primary key, example:

db.version(1).stores({
  table: 'id, idx1, idx2...'
});

Here id is the primary key.

  • db.table.add({id: 1, foo: 'bar'}) will add object with id 1.
  • db.table.add({id: 1, foo: 'bar2'}) 2nd time will fail because id 1 exists.
  • db.table.put({id: 1, foo: 'bar2'}) will update object with id 1.

So what do you really want to do? You say you want to add new object with new key. If so, I suppose the error is that you give the same key second time.

You can also let the id be generated by the db

db.version(2).stores({
  table: '++id, idx1, idx2...'
});

Then you don't need to supply id in calls to add():

  • db.table.add({foo: 'bar'}) will add object with id 1.
  • db.table.add({foo: 'barX'}) 2nd time will add new obj with id 2
  • ...
Heterosexuality answered 18/5, 2018 at 9:46 Comment(1)
Thanks, #David it's perfect answer what I needed.Macilroy

© 2022 - 2024 — McMap. All rights reserved.