欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

nodejs nedb 封装库与使用方法示例

程序员文章站 2022-11-16 10:07:58
本文实例讲述了nodejs nedb 封装库与使用方法。分享给大家供大家参考,具体如下:libs/nedb.jsconst datastore = require('nedb');function d...

本文实例讲述了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, 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);
    })
  });
}
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程序设计有所帮助。