1. 程式人生 > 程式設計 >nodejs nedb 封裝庫與使用方法示例

nodejs nedb 封裝庫與使用方法示例

本文例項講述了nodejs nedb 封裝庫與使用方法。分享給大家供大家參考,具體如下:

libs/nedb.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,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 || {},numAffected) => {
      if (err) {
        return reject(err);
      }
      resolve(numAffected);
    })
  });
}
DB.prototype.remove = function(query,reject) => {
    this.db.remove(query || {},numAffected) => {
      if (err) {
        return reject(err);
      }
      resolve(numAffected);
    })
  });
}
module.exports = (database) => {
  return new DB(database);
}

test.js

const db = require('./libs/nedb')('testdb');
(async function() {
 await db.insert({number: 12});
 await db.insert({number: 11});
 await db.insert({number: 13});
 let res = await db.sort({number: -1}).limit(0,2).find();
 console.log(res);
})();

執行命令

nodemon test.js

希望本文所述對大家node.js程式設計有所幫助。