levelgo

Simple document store with indexing

Usage no npm install needed!

<script type="module">
  import levelgo from 'https://cdn.skypack.dev/levelgo';
</script>

README

levelgo

Indexed collections for LevelDB (inspired by MongoDB)

Build Status

Install

npm i levelgo

Example

import levelgo from 'levelgo'

const db = levelgo('example-db')

db.collection('books')  
db.books.registerIndex({ author: 1 })

await db.books.put('book1', { 
  author: 'Hemingway', 
  title: 'Islands in the Stream',
  year: 1970
})

const book = await db.books.get('book1')
const books = await db.books.find({ author: 'Hemingway' })

API

db = levelgo( location )

  • location {String} path of the LevelDB location to be opened, or in browsers, the name of the IDBDatabase to be opened

db.collection( name )

  • name {String} name of the collection to initialize

Collection methods

db.name.del( id )

  • id {String|Number} primary key of the value to delete

db.name.find( [query] )

  • query {Object} optional selection filter. An index with the same fields must be registered. If blank or empty object, returns all values in the collection.

  • Mongo-style comparison query operators are available:

    • $gt
    • $lt
    • $gte
    • $lte
    • $in
    • $nin
    • $eq
    • $ne
  • Note: null, undefined and "empty string" values are indexed the same as "blank" values.

db.name.findKeys( [query] )

  • query {Object} optional selection filter. An index with the same fields must be registered. If blank or empty object, returns all keys (ids) in the collection.

db.name.get( id )

  • id {String|Number} primary key of the value to retrieve

db.name.put( id, value )

  • id {String|Number} primary key of the value to store
  • value {mixed} any stringify-able value to store in the collection

db.name.registerIndex( fields )

  • fields {Object} fields to be indexed. Always set the value of each field to 1 since only ascending indices are currently supported.

Atomic Batch

batch = db.batch()

batch.name.del( id )

batch.name.put( id, value )

batch.write()

Advanced Example

import levelgo from 'levelgo'

const db = levelgo('example-db')

db.collection('books')

// you can have compound nested indices
db.books.registerIndex({ 
  tags: 1,
  'reviews.stars': 1
})

// batch operations are written atomically
const batch = db.batch()
batch.books.del('book1')
batch.books.put('book2', { 
  author: 'Hemingway', 
  title: 'Islands in the Stream',
  year: 1970,
  reviews: [
    { stars: 5, username: 'taylor' },
    { stars: 4, username: 'river' },
  ],
  tags: ['classic']
})
await batch.write()

// find books that are tagged 'classic' that have at least one review of 4+ stars
const books = await db.books.find({ 
  'reviews.stars': { $gte: 4 },
  tags: 'classic'
})