I’m trying to learn the basics of IndexedDB by creating a trivial notepad application. I’m having difficulties using an ordered list in this environment.
The feature I’m not sure how to implement is having an ordered list of notes.
I first tried implementing the notepad application in WebSQL, and I found it quite easy to select the notes like this:
select * from notes order by position
And when inserting a note at a specified position, I first did …
update notes set position = position + 1 where position >= insert_position
… to shift each note to make space for the new note at position insert_position.
But I saw that WebSQL is actually deprecated.
What are the possibilities to achieve such a feature in IndexedDB? I don’t fully understand how to create an ordered list in an environment such as IndexedDB since a quick query like the above is not applicable.
As a side note, I know it’s possible to store an array in IndexedDB, but then I would just have one record which I’m using each time. I’m rather looking for a way to somehow have an ordered list of all records (each record representing a note), and to be able to update the ordering (like the shifting query above).
Could someone shed some light on the IndexedDB way of an ordered list?
As with many things there are a few ways to crack this nut.
If you were creating an app that orders notes based on creation time, it would be as simple as using an auto-incrementing key (this flag is specified on
objectStorecreation). Note one would have theid(akaprimaryKey) of 1, the second 2 and so forth. This would use the defaultkeyPath, so you could open up a cursor without having to create an index.To order notes by something that could change, such as modified on time, you’d create an index on that field and be sure to specify it when
addingorputtingobjects. You would open up a cursor with a lower bound of, say0(lexicographically ordered keys means this comes before all strings) and leave the upper bound open. You’d then cursor across each row one by one firingonsuccesshandlers until you exhaust your cursor and it returns null inevent. target.result.It sounds like you might be looking to have a field such as “position” and order on that. That’s totally doable with a regular index and cursor, as above. One note of advice would be to make
positionfield a floating point number rather than an integer as with the former you can update the order without having to alter any other rows (position n = ( ( position 1 + position 2 ) / 2 )).