Learn Lowdb small local JSON database

Lowdb is lightweight JSON file-based Node's database. For the construction of small-scale projects do not depend on the server, using LowDB storage and management of data is a very good choice.

A: lowdb use and installation

Root directory in the project installation lowdb command as follows:

npm install --save-dev lowdb

lowdb is based lodash building, so we can use any lodash powerful functions. And we can be used in tandem.
Let's directory structure is such as follows:

|--- lowdb
| |--- node_modules
| |--- app.js
| |--- package.json

Then we add the following code app.js:

const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

const adapter = new FileSync('./db.json');
const db = low(adapter);

db.defaults({posts: [], user: {}, count: 0 }).write();

After saving the above, we perform node app.js the command line, creates a new file in the root directory called db.json in our project, the file code becomes as follows:

{
  "posts": [],
  "user": {},
  "count": 0
}

Code above, the introduction of lowdb package, and then introduced into the adapter FileSync lowdb.
lowdb comes with the adapter has: FileSync, FileAsync and LocalBrowser. The following parameters are optional:

defaultValue: the default value when the file does not exist.
serialize / deserialize: file is read and after the operation before writing.

For example the following code:

const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

const adapter = new FileSync('./db.json', {
  serialize: (data) => JSON.stringify(data),
  deserialize: (data) => JSON.parse(data)
});
const db = low(adapter);

db.defaults({posts: [], user: {}, count: 0 }).write();

As the code, if we db.json no data of the time will recall db.defaults initialization data, otherwise it will use the data stored locally. We can try to change the value of the count, no matter how many times we run the command line in the node, the value is the same, but when we put db.json contents removed, and then we run, discover the latest content is written go in.

Code above, if we put this into the above code is as follows:

const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

const adapter = new FileSync('./db.json', {
  serialize: (data) => console.log(data),
  deserialize: (data) => console.log(data)
});
const db = low(adapter);

db.defaults({posts: [], user: {}, count: 30 }).write();

Then run from the command line, the first printed before being written to serialize} {empty object. Db.defaults operation will then perform the write data corresponding to the file db.json, and we'll perform operations on the file deserialize read, then the command line will be printed {posts: [], user: {}, count: 30}. After the printing is complete, we do not do anything, and finally we come to look under db.json file into the undefined. Therefore, we can determine the serialize and deserialize these two operations is completed, they will write to the file . If no value is written or operation, then the contents of the file becomes undefined. When the file becomes undefined, we again perform the above code can be seen db.defaults ({posts: [], user: {}, count: 30}) write (); This code will not be written. entrant. Then we can guess the meaning of this code will determine whether the file has no content, if not the content, then the data will be written to the file, otherwise it will not do anything. We can then db.json contents of all deleted files, we again run under node app.js command, you can see that this time the data will be written into it.

1. Data Set

We can set a field to db.json data inside the data, such as the following code:

const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

const adapter = new FileSync('./db.json', {
  serialize: (data) => JSON.stringify(data),
  deserialize: (data) => JSON.parse(data)
});
const db = low(adapter);

db.defaults({posts: [], user: {}, count: 30 }).write();

// 设置数据 
db.set("user.name", 'kongzhi').write();

Then our db.json the data becomes as follows:

{"posts":[],"user":{"name":"kongzhi"},"count":30}

2. Get the data

We can get to json file value of a field, and then add data manipulation, or delete data operations, in short, we can manipulate the data, the following code:

the require Low = const ( 'lowdb' ); 
const FileSync = the require ( 'lowdb / Adapters / FileSync' ); 

const Adapter = new new FileSync ( './ db.json' , { 
  the serialize: (Data) => the JSON.stringify ( Data), 
  Deserialize: (Data) => the JSON.parse (Data) 
}); 
const DB = Low (Adapter); 

db.defaults ({Posts: [], User: {}, COUNT: 30 .}) Write ( ); 

// set the data 
db.set ( "user.name", 'kongzhi' ) .write (); 

// GET data, and then add a data into account, the final written document to go inside. 
db.get ( 'posts') push ( {' id ':. 1,' title ':'

Our db.json file code becomes as follows:

{"posts":[{"id":1,"title":"welcome to hangzhou"}],"user":{"name":"kongzhi"},"count":30}

3. update the data, we can update certain pieces of data. As shown in the following code:

the require Low = const ( 'lowdb' ); 
const FileSync = the require ( 'lowdb / Adapters / FileSync' ); 

const Adapter = new new FileSync ( './ db.json' , { 
  the serialize: (Data) => the JSON.stringify ( Data), 
  Deserialize: (Data) => the JSON.parse (Data) 
}); 
const DB = Low (Adapter); 

db.defaults ({Posts: [], User: {}, COUNT: 30 .}) Write ( ); 

// set the data 
db.set ( "user.name", 'kongzhi' ) .write (); 

// GET data, and then add a data into account, the final written document to go inside. 
// db.get ( 'Posts') Push ({' ID ':.. 1,' title ':'

// use the update data to update the default values where n is the count, the count in db.json default is 30, the last write into 
db.update ( 'count', n = > n + 1) .write () ;

After running db.json data code as follows:

{"posts":[{"id":1,"title":"welcome to hangzhou"}],"user":{"name":"kongzhi"},"count":31}

Note: Due to our lowdb based lodash, so we can use all the methods and properties of lodash.

4. find locate data fields

We can search for data in a field db.json. Code as follows:

the require Low = const ( 'lowdb' ); 
const FileSync = the require ( 'lowdb / Adapters / FileSync' ); 

const Adapter = new new FileSync ( './ db.json' , { 
  the serialize: (Data) => the JSON.stringify ( Data), 
  Deserialize: (Data) => the JSON.parse (Data) 
}); 
const DB = Low (Adapter); 

db.defaults ({Posts: [], User: {}, COUNT: 30 .}) Write ( ); 

// set the data 
db.set ( "user.name", 'kongzhi' ) .write (); 

// GET data, and then add a data into account, the final written document to go inside. 
// db.get ( 'Posts') Push ({' ID ':.. 1,' title ':'

// use the update data to update the default values where n is the count, the count in db.json default is 30, the last write into 
db.update ( 'count', n => n +. 1 ) .write () ; 

// Find data 
const = db.get value ( 'Posts') Find ({ 'ID':. 1. }) value ();. 
the console.log (value);

If our db.json code is as follows:

{"posts":[{"id":1,"title":"welcome to hangzhou"}],"user":{"name":"kongzhi"},"count":33}

Therefore, we ( 'posts') find by db.get.. ({ 'Id': 1}) value () can be obtained after the value, as follows:

5. lowdb 的 API

1. low (adapter): it returns lodash having specific properties and functions.
2. DB [...] Write () / value ():... Write () method is to write data, value () method data is read.
3. db.getState () / setState () :. State acquisition / setting of the database.
4. db._ solid column of lodash database. We can use this function to add our own or third-party mixins. For example lodash-id (https://github.com/typicode/lodash-id)

mixins use Liezi follows:

code show as below:

the require Low = const ( 'lowdb' ); 
const FileSync = the require ( 'lowdb / Adapters / FileSync' ); 

const Adapter = new new FileSync ( './ db.json' , { 
  the serialize: (Data) => the JSON.stringify ( Data), 
  Deserialize: (Data) => the JSON.parse (Data) 
}); 
const DB = Low (Adapter); 

db.defaults ({Posts: [], User: {}, COUNT: 30 .}) Write ( ); 

// use mixed mode mixin to expand our own methods 
DB ._ mixin ({. 
  getSecondData: function (ARR) {
     return ARR [. 1 ]; 
  } 
}); 
//The method calls getSecondData acquired second data posts 
const db.get XX = ( 'posts' ) .getSecondData () value ();. 
The console.log (XX);

If our data db.json code is as follows:

{
  "posts":[
    {"id":1,"title":"welcome to hangzhou"},
    {"id":2,"title":"welcome to hangzhou"}
  ],
  "user":{"name":"kongzhi"},
  "count":33
}

We run the node app.js command, you can see, we can get into the inside of the second data array, as shown below:

6. db.getState / db.setState obtain database status / setting state of the database, the following code shows:

const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

const adapter = new FileSync('./db.json', {
  serialize: (data) => JSON.stringify(data),
  deserialize: (data) => JSON.parse(data)
});
const db = low(adapter);

db.defaults({posts: [], user: {}, count: 30 }).write();

// 获取数据库的状态
console.log(db.getState());

const newState = {}
db.setState(newState);

console.log('-----------');
console.log(db.getState());

db.json If the data is as follows:

{
  "posts":
    [
      {"id":1,"title":"welcome to hangzhou"},
      {"id":2,"title":"welcome to hangzhou"}
    ],
  "user":{"name":"kongzhi"},
  "count":33
}

Operating results as shown below:

7. Other data manipulation json

Db.json such data as follows:

{
  "posts":
    [
      {"id":1,"title":"welcome to hangzhou"},
      {"id":2,"title":"welcome to hangzhou"}
    ],
  "user":{"name":"kongzhi"},
  "count":33
}

1. Check db.json there is no 'posts' this field is present. Test code as follows:

db.has ( 'Posts') value ();.   // if the field will return true, otherwise returns false.

2. Set the value set 

db.set ( 'posts', []) Write ();. // run is completed, it will posts on a field to an empty array [];

3. Obtain the values ​​of specific fields of 

db.get ( 'Posts') Map ( 'ID') value ();.. // After execution returns [1, 2]

4. Get the number of 

. db.get ( 'Posts') size () value ();. // returns the array length of 2

The value of the specific information acquired

db.get ( 'Posts [0] .id') value ();. // returns 1.

6. Update Information

db.get('posts')
  .find({title: 'welcome to hangzhou'})
  .assign({name: 'kongzhi'})
  .write();

As the code, we can see that we get posts in this field, and to find the find by keyword {title: 'welcome to hangzhou'} so, if found, assign values ​​to put it into an object inside. If none is found, this value will be added inside the object, so the above returns the following results:

{
  "posts":[
    {"id":1,"title":"welcome to hangzhou","name":"kongzhi"},
    {"id":2,"title":"welcome to hangzhou"}
  ],
  "user":{"name":"kongzhi"},
  "count":33
}

If we take the above statement into the following statement, it will change the corresponding value:

db.get('posts')
  .find({name: 'kongzhi'})
  .assign({name: 'xxx'})
  .write();

Then the result becomes as follows:

{
  "posts":[
    {"id":1,"title":"welcome to hangzhou","name":"xxx"},
    {"id":2,"title":"welcome to hangzhou"}
  ],
  "user":{"name":"kongzhi"},
  "count":33
}

7. Delete Information

db.get('posts')
  .remove({name: 'xxx'})
  .write();

Then the result becomes the following:

{
  "posts":[
    {"id":2,"title":"welcome to hangzhou"}
  ],
  "user":{"name":"kongzhi"},
  "count":33
}

8. Remove Attribute

db.unset('posts[0].id').write();

Then the result becomes as follows:

{"posts":[
    {"title":"welcome to hangzhou"}
  ],
  "user":{"name":"kongzhi"},
  "count":33
}

9. deep copy

var xx = db.get('posts').cloneDeep().value();
console.log(xx); // 打印:[ { title: 'welcome to hangzhou' } ]

Learn more knowledge, see here

Guess you like

Origin www.cnblogs.com/tugenhua0707/p/11403202.html