node.js封装数据库增删改查

筅森魡賤 提交于 2019-11-27 10:18:23

数据库增删改查的封装

小编不容易

const sql = {
  insert: function (Collection, insertData) {
    return new Promise((resolve, reject) => {
      Collection.insertMany(insertData, (err) => {
        if (err) throw err;
        resolve()
      })
    })
  },
  find (Collection, whereObj, showObj) {
    // return new Promise(function (resolve, reject) {})
    // return new Promise(function (resolve, reject) { // 异步操作})
    // return new Promise(function (resolve, reject) { // 异步操作 - reslove(data)})
    return new Promise(function (resolve, reject) {
      Collection.find(whereObj, showObj).exec((err, data) => {
        if (err) throw err;
        resolve(data)
      })
    })

  },
  sort: function * (Collection, whereObj, showObj, sortObj) {
    return new Promise(function (resolve, reject) {
      Collection.find(whereObj, showObj).sort(sortObj).exec((err, data) => {
        if (err) throw err;
        resolve(data)
      })
    })
  },
  update (Collection, whereObj, updateObj, updateType) {
    // Collection['updateOne']()   <===> Collection.updateOne()
    // style.width = '100px'    style['width'] = '100px';
    return new Promise((resolve, reject) => {
      updateType = updateType || 'updateOne'
      Collection[updateType](whereObj, updateObj, (err) => {
        if (err) throw err;
        resolve();
      })
    })
  },
  delete (Collection, whereObj, deleteType) {
    return new Promise((resolve, reject) => {
      deleteType = deleteType || 'deleteOne';
      Collection[deleteType](whereObj, (err) => {
        if (err) throw err;
        resolve();
      })
    })
  },
  distinct(Collection, type) {
    return new Promise((resolve, reject) => {
      Collection.distinct(type).exec((err, data) => {
        if (err) throw err;
        resolve(data)
      })

    })
  }
}

module.exports = sql;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!