Skip to content

JSON 数据库

基础

bash
- 小数据量: 0~100M(单库)
- json数据库
- 兼容lodash语法

数据文件位置

打包前:项目根目录

bash
electron-egg/data/xxx.json

打包后:软件缓存目录

bash

# windows (例子)
C:\Users\Administrator\AppData\Roaming\软件名(如:ee)\data\xxx.json

# macOS (例子)
Users/apple/Library/Application Support/软件名(如:ee)/data/xxx.json

# Linux (例子)
$XDG_CONFIG_HOME or ~/.config/软件名(如:ee)/data/xxx.json

示例

  • 连接数据
js
"use strict";

const { Service } = require("ee-core");
// 框架提供的数据库对象
// ee-core:v2.0.1
const Storage = require("ee-core/storage");
const _ = require("lodash");

/**
 * 数据存储
 * @class
 */
class StorageService extends Service {
  constructor(ctx) {
    super(ctx);

    // jsondb数据库

    // ee-core所使用的库
    this.systemDB = Storage.connection("system");

    // demo库
    let jsondbOptions = {
      driver: "jsondb",
    };
    this.demoDB = Storage.connection("demo", jsondbOptions);
  }
}

module.exports = StorageService;
  • 增加数据
js
/*
* 增 Test data
*/
async addTestData(user) {
  const key = this.demoDBKey.test_data;
  if (!this.demoDB.db.has(key).value()) {
    this.demoDB.db.set(key, []).write();
  }

  const data = this.demoDB.db
    .get(key)
    .push(user)
    .write();

  return data;
}
  • 删除数据
bash

/*
* 删 Test data
*/
async delTestData(name = '') {
  const key = this.demoDBKey.test_data;
  const data = this.demoDB.db
    .get(key)
    .remove({name: name})
    .write();

  return data;
}
  • 修改数据
bash
/*
* 改 Test data
*/
async updateTestData(name= '', age = 0) {
  const key = this.demoDBKey.test_data;
  const data = this.demoDB.db
    .get(key)
    .find({name: name}) // 修改找到的第一个数据,貌似无法批量修改 todo
    .assign({age: age})
    .write();

  return data;
}
  • 查找数据
bash

/*
* 查 Test data
*/
async getTestData(age = 0) {
  const key = this.demoDBKey.test_data;
  let data = this.demoDB.db
    .get(key)
    //.find({age: age}) 查找单个
    .filter(function(o) {
      let isHas = true;
      isHas = age === o.age ? true : false;
      return isHas;
    })
    //.orderBy(['age'], ['name']) 排序
    //.slice(0, 10) 分页
    .value();

  if (_.isEmpty(data)) {
    data = []
  }

  return data;
}

/*
* all Test data
*/
async getAllTestData() {
  const key = this.demoDBKey.test_data;
  if (!this.demoDB.db.has(key).value()) {
    this.demoDB.db.set(key, []).write();
  }
  let data = this.demoDB.db
    .get(key)
    .value();

  if (_.isEmpty(data)) {
    data = []
  }

  return data;
}