Skip to content
Maximilian Stroh edited this page Jan 22, 2014 · 3 revisions

This is a tiny abstraction over several persistence options you can use out-of-the-box to get running even faster.

###simple store

A thin wrapper over Chromium's localStorage. Basically it's a key-value approach, where the keys and values are stored as strings. It's the easiest storage option you have, with one caveat: it's blocking. So do not use it to handle much data, localStorage is therefore quite useful for something like settings and configurations.

db = DataStore.create "simple"
db.set "my key", "my value" # insert into the datastore
db.set "another key", {a: 1, b: 2, c: 3} # insert objects, ...
value = db.get "my key" # retrieve any value
db.delete "my key" # remove the record from the datastore
db.count() # 1
db.clear() # remove all data at once

###relational store

Want some SQL? If like to store your data in a relational database, just use this datastore. It's a wrapper around Chromium's built-in Web SQL Database, which actually just is SQLite. I smoothened the somewhat quirky browser API, look at the sample code:

db = DataStore.create "relational"

### inserting stuff ###
db.run "CREATE TABLE IF NOT EXISTS foo (id unique, text)" # create a table
db.run "INSERT INTO foo (id, text) VALUES (1, 'synergies')" # just insert, fire-and-forget-style
db.run "INSERT INTO foo (id, text) VALUES (2, 'luyao')", -> console.log "insertion done!" # insert with callback

### query stuff ###
db.run "SELECT * FROM foo", (rows) -> console.log rows # array of result record objects

###document store

If you like MongoDB and have data that better fits in a document store, here you have it. NeDB is MongoDB's little brother, and basically an embeddable pure Javascript database with an API similar to MongoDB. To get started as fast as possible, I wrapped the module (which resides in /app/assets/node_modules) so you can just think in terms of collections:

# the data I want to store:
doc = {first_name: "Maximilian", last_name: "Stroh", github_name: "Anonyfox"}

# create/use a collection: 
db = DataStore.create "document"
developers = db.collection "developers"

# standard operations
developers.insert doc, (error, newDoc) -> console.log "insertion: ", error, newDoc
developers.find {first_name: "Maximilian"}, (error, docs) -> console.log "found documents: ", docs
developers.findOne {first_name: "Maximilian"}, (error, foundDoc) -> console.log "found document: ", doc
# ... and so on.

Please have a look at https://github.com/louischatriot/nedb for further informations. Note that I used the actual collection, and not "db" as louischatriot does on the NeDB page, but this is only a naming difference!

Clone this wiki locally