Nedb

What is NeDB?

NeDB is a javascript database. https://github.com/louischatriot/nedb

From their website:

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

Install

Using npm:

npm install nedb --save

Using yarn:

yarn add nedb

Usage

NeDB is a pretty similar MongoDB when it comes to the sintaxe.

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) // we should get something like // { title: 'Some Project title', \_id: 'fasd8fa0df9d9d98' } }) projects.find({}, (err, docs) => { if (err) console.warn(err) // 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 :)

Pedro Luz
A personal blog by Pedro Luz about coding, coding, habit building, and a few things more.(Psst... I am open to opportunities.)
Reach out to me on your favorite social :)© 2020 Pedro Luz