nedb是一个表对应一个文件,使用时需要注意,下面直接上代码说明了
index.js
import Datastore from 'nedb'
import path from 'path'
class DB {
constructor () {
if (DB.prototype.__Instance === undefined) {
DB.prototype.__Instance = this
this.init()
}
return DB.prototype.__Instance.db;
}
init(){
this.db={};
var carDriverDB = new Datastore({
autoload: true,
filename: path.join(__userData,'db/carDriverDB.db')
})//
var carDB = new Datastore({
autoload: true,
filename: path.join(__userData,'db/carFlightDB.db')
})//
this.db.carDriverDB=carDriverDB;
this.db.carDB=carDB;
}
}
// 单例模式
export default new DB();
db.js
const Datastore = require('nedb');
function DB(database) {
let options = {
filename: database,
autoload: true,
};
this.db = new Datastore(options);
}
DB.prototype.limit = function(offset, limit) {
this.offset = offset || 0;
this.limit = limit || 15;
return this;
}
DB.prototype.sort = function(orderby) {
this.orderby = orderby;
return this;
}
DB.prototype.find = function(query, select) {
return new Promise((resolve, reject) => {
let stmt = this.db.find(query || {});
if (this.orderby !== undefined) {
stmt.sort(this.orderby);
}
if (this.offset !== undefined) {
stmt.skip(this.offset).limit(this.limit);
}
if (select != undefined) {
stmt.projection(select || {});
}
stmt.exec((err, docs) => {
if (err) {
return reject(err);
}
resolve(docs);
})
})
};
DB.prototype.findOne = function(query, select) {
return new Promise((resolve, reject) => {
let stmt = this.db.findOne(query || {});
if (this.sort !== undefined) {
stmt.sort(this.sort);
}
if (select != undefined) {
stmt.projection(select || {});
}
stmt.exec((err, doc) => {
if (err) {
return reject(err);
}
resolve(doc);
})
})
}
DB.prototype.insert = function(values) {
return new Promise((resolve, reject) => {
this.db.insert(values, (err, newDoc) => {
if (err) {
return reject(err);
}
resolve(newDoc);
})
})
}
DB.prototype.update = function(query, values, options) {
return new Promise((resolve, reject) => {
this.db.update(query || {}, values || {}, options || {}, (err, numAffected) => {
if (err) {
return reject(err);
}
resolve(numAffected);
})
});
}
DB.prototype.remove = function(query, options) {
return new Promise((resolve, reject) => {
this.db.remove(query || {}, options || {}, (err, numAffected) => {
if (err) {
return reject(err);
}
resolve(numAffected);
})
});
}
export default DB;
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210119110910313.png)
引入如下
import db from './db'
Vue.prototype.$db = db;
//使用方法
this.$db.carFlightDB
.find({ planDate: that.planDate })
.sort({ findex: 1, orderbyField: 1, _id: 1 })
.exec(function(err, docs) {
if (err) {
console.log(err);
}
that.flightList = docs;//把结果赋值
});