Search code examples
dexie

Dexiedb Put method not working when adding primary key as argument


i am using dexiedb for my angular project. I have a database with a comments table. I would like to add the user inputs to the database and i am using table.put(item, [key]). I want to only add in the first row, so primary key = 0, thats why i specify the key. But it is not working.

Below is my code snippet. I am getting error when having the primary key as argument.

Failed to execute 'put' on 'IDBObjectStore': The o… in-line keys and the key parameter was provided.",

@Injectable()
export class DexieService{

    onNewComment = new EventEmitter<Comments>();

    contactDB: Dexie;

    constructor(){
        this.contactDB = new Dexie('contact');
        this.contactDB.version(1).stores({
            comments:'++id,comment'
        })
    }

addComment(comment: Comments): Promise<any>{   
            return(
                this.contactDB.table('comments').put(comment,0)
                   .then((result) =>{ 
                       this.onNewComment.next(comment);
                       return (result);
                   })
               )            
    }

Expected result should be that when any new comments are added, it will always go to first row with primary key = 0 as the primary key already exists


Solution

  • Your primary key (++id) is inbound, which means you can only specify the key within the object itself and do not need to use the optional key parameter. The API will fail if using the optional key argument unless the primary key is outbound. This API mirrors the raw IndexedDB's IDBObjectStore.put() method that works the same for inbound keys.

    Instead, use:

    this.contactDB.table('comments').put({...comment, id: 0})