Last active
May 25, 2020 20:41
-
-
Save bennycode/1eb2b190f64602678988694477bcf3d5 to your computer and use it in GitHub Desktop.
Auto incremental primary keys with Dexie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Title</title> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<script src="bower_components/dexie/dist/dexie.js"></script> | |
</head> | |
<body> | |
<script> | |
const dbName = 'MyDatabase'; | |
const storeName = 'friends'; | |
let db = new Dexie(dbName); | |
db.delete().then(() => { | |
db = new Dexie(dbName); | |
const schema = ( | |
obj = {}, | |
obj[storeName] = '++id, name, age', | |
obj | |
); | |
db.version(1).stores(schema); | |
db[storeName].hook('creating', function (primaryKey, friend) { | |
console.log(`Saving "${friend.name}" but we don't now the primary key yet ("${primaryKey}").`); | |
this.onsuccess = function (primaryKey) { | |
console.log(`Saved "${friend.name}" with primary key "${primaryKey}".`); | |
}; | |
return undefined; | |
}); | |
const friends = [ | |
{name: 'Alfred', age: 42}, | |
{name: 'Laura', age: 26}, | |
{name: 'Daniel', age: 29} | |
]; | |
db.friends.bulkAdd(friends) | |
.then(() => { | |
return db[storeName].toArray(); | |
}) | |
.then((friends) => { | |
console.log(`Loaded "${friends.length}" friends. Now the primary key is also part of their values...`); | |
friends.forEach((record) => console.log(`Primary key of "${record.name}" is "${record.id}".`)); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment