electron集成nedb,实现本地数据存储

847 阅读2分钟
什么是nedb?

Nedb是一个基于Node.js的嵌入式数据库,它在内存中存储数据,同时也支持将数据持久化到磁盘。它的设计灵感来自MongoDB,提供了类似的API和查询语言,而且在运行程序时不用启动独立的数据库服务器。

nedb的优点
  1. 内存存储和持久化支持

    • Nedb可以将数据存储在内存中,这样可以快速访问和修改数据。
    • 同时,Nedb也支持将数据持久化到磁盘上的文件,确保数据在应用程序重启后仍然可用。
  2. 无需启动独立的数据库服务器

    • 与传统的关系型数据库或MongoDB不同,Nedb是一个嵌入式数据库,它直接在Node.js应用程序的上下文中运行,无需启动独立的数据库服务器进程。
  3. 轻量级和易于集成

    • Nedb的实现非常轻量,适合嵌入到Node.js应用程序中作为数据存储的一部分。
    • 它易于安装和使用,并且不需要复杂的配置或管理。

步骤

  1. npm install nedb安装依赖
  2. 封装nedb
import Datastore from 'nedb'
import path from 'path'

// 定义数据库文件路径
const dbPath = path.join(__dirname, 'test.db')

// 创建并加载数据库
const db = new Datastore({ filename: dbPath, autoload: true })

// 导出数据库实例
export default db

// 插入文档
export const insertDocument = (doc, callback) => {
  db.insert(doc, (err, newDoc) => {
    if (callback) {
      callback(err, newDoc)
    }
  })
}

// 更新文档
export const updateDocument = (query, update, options, callback) => {
  db.update(query, update, options, (err, numAffected, affectedDocuments, upsert) => {
    if (callback) {
      callback(err, numAffected, affectedDocuments, upsert)
    }
  })
}

// 查询文档
export const findDocuments = (query, projection, callback) => {
  db.find(query, projection, (err, docs) => {
    if (callback) {
      callback(err, docs)
    }
  })
}

// 删除文档
export const deleteDocument = (query, options, callback) => {
  db.remove(query, options, (err, numRemoved) => {
    if (callback) {
      callback(err, numRemoved)
    }
  })
}

  1. 在electron主进程中引入db实例并挂载
import db from '../utils/nedb.js'
import { app, BrowserWindow, Menu } from 'electron'
const createMainWin = (): BrowserWindow => {
    // 建立数据库连接
    db
    // 主窗口
    const win = new BrowserWindow({
        width: 1334,
        height: 750,
        minWidth: 1334,
        minHeight: 750,
        resizable: false,
        icon: getIcon(),
        show: false,
        // 创建无边框窗口
        frame: false,
        titleBarStyle: 'hidden',
        webPreferences: {
          // webSecurity: false,
          offscreen: false,
          nodeIntegration: true, // 是否集成nodejs
          contextIsolation: true, // 是否开启上下文隔离
          preload: join(__dirname, '../preload/index')
        }
    })
    ...
}
  1. nedb数据库的使用示例
import { deleteDocument, findDocuments, insertDocument, updateDocument } from '../utils/nedb.js'
// 示例:在其他页面的某个函数或模块中使用数据库操作
const documentToInsert = { name: 'xiaoming', age: 18 };

insertDocument(documentToInsert, (err, newDoc) => {
  if (err) {
    console.error('Error inserting document:', err);
  } else {
    console.log('Inserted document:', newDoc);
  }
});

// 查询文档示例
// `$eq`: 等于
// `$lt`: 小于
// `$lte`: 小于等于
// `$gt`: 大于
// `$gte`: 大于等于
// `$ne`: 不等于
// `$in`: 包含在数组中
// `$nin`: 不包含在数组中
const query = { age: { $gte: 20 } };
const projection = { _id: 0, name: xiaoming, age: 1 };

findDocuments(query, projection, (err, docs) => {
  if (err) {
    console.error('Error finding documents:', err);
  } else {
    console.log('Found documents:', docs);
  }
});

// 更新文档示例
const updateQuery = { name: 'xiaoming' };
const update = { $set: { age: 26 } };
const options = { multi: false, returnUpdatedDocs: true };

updateDocument(updateQuery, update, options, (err, numAffected, affectedDocuments, upsert) => {
  if (err) {
    console.error('Error updating document:', err);
  } else {
    console.log('Updated', numAffected, 'documents.');
    console.log('Affected documents:', affectedDocuments);
  }
});

// 删除文档示例
const deleteQuery = { name: 'xiaoming' };
const deleteOptions = {};

deleteDocument(deleteQuery, deleteOptions, (err, numRemoved) => {
  if (err) {
    console.error('Error deleting document:', err);
  } else {
    console.log('Deleted', numRemoved, 'documents.');
  }
});