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:
1
|
npm install nedb --save
|
Using yarn:
Usage
NeDB is a pretty similar MongoDB when it comes to the sintaxe.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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:
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
// 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:
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
// 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 :)