LowDB
Need a quick way to get a local database?
需要一种神速的本地存储方式吗?
LowDB是基于node的纯JSON文件数据库,这是它readMe文件的中文翻译。
Example(示例)
var low = require('lowdb')
var db = low('db.json')
db('posts').push({ title: 'lowdb is awesome'})
数据库被自动存往db.json
Database is automatically saved to db.json
{
"posts": [
{ "title": "lowdb is awesome" }
]
}
你能使用任何lodash方法来查询和操纵数据库
You can query and manipulate it using any lodash method
db('posts').find({ title: 'lowdb is awesome' })
Install(安装)
npm install lowdb --save
Features(特性)
- Small(轻量级)
- Serverless(不需要服务器)
- lodash rich API(lodash丰富的API)
- In-memory or disk-based(基于内存和硬盘的存储)
- Hackable (mixins, id, encryption, ...)
lowDB非常容易学习,因为它只有八种方法和属性
It's also very easy to learn and use since it has only 8 methods and properties.
json-server 、
jsonplaceholder 和 other projects都由lowDB强力驱动
lowdb powers json-server package, jsonplaceholder website and other projects.
API
low([filename, options])
创建一个基于硬盘或者内存的数据库实例。如果文件名参数存在,那么这个文件就会被载入或者创建。
Creates a disk-based or in-memory database instance. If a filename is provided, it loads or creates it.
var db = low() // in-memory
var db = low('db.json') // disk-based
当提供了filename
参数时,你能设置选项
When a filename is provided you can set options.
var db = low('db.json', {
autosave: true, // automatically save database on change (default: true)
async: true // asynchronous write (default: true)
})
low.stringify(obj) and low.parse(str)
重写这些选项来自定义JSON的字符串化和解析
Overwrite these methods to customize JSON stringifying and parsing.
__ db._ __
数据库lodash实例,你能用它来添加你需要的实用功能或者第三方库
Database lodash instance. Use it for example to add your own utility functions or third-party libraries.
db._.mixin({
second: function(array) {
return array[1]
}
})
var song1 = db('songs').first()
var song2 = db('songs').second()
db.object
用以操纵底层数据库对象
Use whenever you want to access or modify the underlying database object.
if (db.object.songs) console.log('songs array exists')
db.save([filename])
保存数据库到指定文件
Saves database to file.
var db = low('db.json')
db.save() // saves to db.json
db.save('copy.json')
注意:如果你直接操纵了数据库对象,你需要手动调用save
来保存
Note: In case you directly modify the content of the database object, you'll need to manually call save
delete db.object.songs
db.save()
db.saveSync([filename])
db.save()
的同步执行版本
Synchronous version of db.save()
Guide(指南)
Operations(操作)
你可以在LowDB上使用所有的lodash API,所以有很多方式查询操纵数据,下面是几个入门级示例
With LowDB you get access to the entire lodash API, so there's many ways to query and manipulate data. Here are a few examples to get you started.
请一定到牢记数据是由参考返回的【?】,这意味着对返回的对象的操作可能会导致数据库的改变,可以使用.cloneDeep()
来避免这种状况。
Please note that data is returned by reference, this means that modifications to returned objects may change the database. To avoid such behaviour, you need to use .cloneDeep()
.
当然,链式方法的执行是惰性的,也是说,value()
调用后语句才会执行。
Also, the execution of chained methods is lazy, that is, execution is deferred until .value()
is called.
排序挑选出前五首歌
Sort the top five songs.
db('songs')
.chain()
.where({published: true})
.sortBy('views')
.take(5)
.value()
检索歌曲标题
Retrieve song titles.
db('songs').pluck('titles')
获取歌曲数量
Get the number of songs.
db('songs').size()
对songs
数据库进行深度克隆
Make a deep clone of songs.
db('songs').cloneDeep()
更新一首歌的数据
Update a song.
db('songs')
.chain()
.find({ title: 'low!' })
.assign({ title: 'hi!'})
.value()
移除歌曲
Remove songs.
db('songs').remove({ title: 'low!' })
Id support(支持ID)
通过ID来检索数据是非常有用的,特别是在服务器中。为了给LowDB添加基于ID的资源管理支持,你有两个选项。
Being able to retrieve data using an id can be quite useful, particularly in servers. To add id-based resources support to lowdb, you have 2 options.
underscore-db为创建和操作基于ID的资源提供了一系列辅助
underscore-db provides a set of helpers for creating and manipulating id-based resources.
var db = low('db.json')
db._.mixin(require('underscore-db'))
var songId = db('songs').insert({ title: 'low!' }).id
var song = db('songs').getById(songId)
uuid 返回一个独一无二的id
uuid returns a unique id.
var uuid = require('uuid')
var songId = db('songs').push({ id: uuid(), title: 'low!' }).id
var song = db('songs').find({ id: songId })
Encryption support(加密支持)
在某些情况下,你可能希望让别人难以解读数据库中的内容。你能通过重写low.stringify
和low.parse
来添加自定义加密方法。
In some cases, you may want to make it harder to read database content. By overwriting, low.stringify
and low.parse
, you can add custom encryption.
var crypto = require('crypto')
var cipher = crypto.createCipher('aes256', secretKey)
var decipher = crypto.createDecipher('aes256', secretKey)
low.stringify = function(obj) {
var str = JSON.stringify(obj)
return cipher.update(str, 'utf8', 'hex') + cipher.final('hex')
}
low.parse = function(encrypted) {
var str = decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8')
return JSON.parse(str)
}