NeDB Intro

What is NeDB?

NeDB is a javascript database.

From their website:

Embedded persistent or in memory database for Node.js, nw.js, Electron and browsers, 100% JavaScript, no binary dependency.


Install

NPM: npm install nedb --save

YARN: yarn add nedb --save


Usage

NeDB is a pretty similar MongoDB way of coding.

import Datastore from 'nedb'

const projects = new Datastore({
  filename: 'projects.db',
  autoload: true
})

const project = {
  title: 'Some Project Title'
}

projects.insert(project, (err, doc) => {
  if (err) console.warn(err)

  console.log(doc)

  // we should get something like
  // { title: 'Some Project title', _id: 'fasd8fa0df9d9d98' }
})

projects.find({}, (err, docs) => {
  if (err) console.warn(err)
  console.log(docs)

  // we should get something like
  // [{ title: 'Some Project title', _id: 'fasd8fa0df9d9d98' }]
})

Promises

NeDB does not support Promises or async/await, but we can still use Promises, like this:

// create the connection
const projects = new Datastore({
  filename: 'projects.db',
  autoload: true
})

// create a method to wrap the insert
const createProject = (title) => {
  const project = {
    title
  }

  return new Promise((resolve, reject) => {
    projects.insert(project, (err, doc) => {
      err ? reject(err) : resolve(doc)
    })
  })
}

// create a method to wrap the fetch
const fetchProjects = () => {
  return new Promise((resolve, reject) => {
    projects.find({}, (err, docs) => {
      err ? reject(err) : resolve(docs)
    })
  })
}

And now to use our methods:

// now we create a project like this
createProject('Some Project Title')
  .then(project => {
    console.log(project)
  })
  .catch(err => {
    console.warn(err)
  })

fetchProjects()
  .then(projects => {
    console.info(projects)
  })
  .catch(err => {
    console.warn(err)
  })

How easy is that :)

Share Comments
comments powered by Disqus