Level / memdown

In-memory abstract-leveldown store for Node.js and browsers.
MIT License
287 stars 37 forks source link

Only stores strings? #93

Closed gpresland closed 7 years ago

gpresland commented 7 years ago

get always seems to return a string, even if you used a number or object as the value in a put,

I can't find any documentation that shows any example, or has any explanation other than with a string.

According to LevelDB, I should be able to store any type of key and value I want as they are stored as

LevelDB supports arbitrary byte arrays as both keys and values..

and

put() is the primary method for inserting data into the store. Both the key and value can be arbitrary data objects.

Is there something I am not understanding or..?

vweevers commented 7 years ago

We recognize the lack of documentation on this and that "arbitrary data objects" is misleading. The storage of keys and values like these is supported through the use of an encoding. Such an encoding converts your values (like numbers) to something supported by the underlying store - and back. The default encoding of levelup is utf8, and you can set different encodings for keys and values.

You'll most likely want the json encoding. Here's how (with levelup@1.x):

const levelup = require('levelup')
const memdown = require('memdown')

const db = levelup('/my-db', {
    db: memdown,
    keyEncoding: 'json',
    valueEncoding: 'json'
})

db.put(12, 12, function (err) {
    if (err) throw err

    db.get(12, function (err, value) {
        console.log(typeof value, value) // "number 12"
    })
})
vweevers commented 7 years ago

Also note that the usage will change in the upcoming levelup@2 release, and the README has already been modified in anticipation of this.

For relevant documentation on the current levelup, please see: https://github.com/Level/levelup/tree/v1.3.9#json

gpresland commented 7 years ago

Thanks for the explanation. 👍