使用nodejs封装mongodb查询、修改、增加、删除操作【单例模式】

配置mongodb数据库

config.js文件

const app = {
  dbUrl: 'mongodb://localhost:27017', //数据库地址
  dbName:'test'  //连接数据库名称
}

module.exports = app

封装mongodb的CRUD

db.js文件

const MongoClient = require('mongodb').MongoClient  //引入mongodb模块
const Config = require('./config')   //引入配置

// 定义类
class Db {

  static getInstance() { // 静态方法  使用单例模式
    if (!Db.instance) {
      Db.instance = new Db()
      // console.log('实例化DB类');
    }
    return Db.instance
  }

  constructor() {
    this.connect()   // 刚初始化时  就连接数据库
    this.dbClient = ''   // 连接对象
  }

  // 连接数据库方法
  connect() {
    let _this = this
    return new Promise((resolve, reject) => {
      if (!_this.dbClient) {
        MongoClient.connect(Config.dbUrl, { useUnifiedTopology: true }, (err, client) => {
          if (err) {
            reject(err)
          } else {
            _this.dbClient = client.db(Config.dbName)
            // console.log(_this.dbClient);
            resolve(_this.dbClient)
          }
        })
      } else {
        resolve(_this.dbClient);

      }
    })
  }

  // 查找数据方法
  find(collectionName, json) {
    // console.log(collectionName,json);
    return new Promise((resolve, reject) => {
      this.connect().then(db => {
        const result = db.collection(collectionName).find(json)
        result.toArray((err, docs) => {
          if (err) {
            reject(err)
            return
          }
          resolve(docs)
        })
      })
    })
  }

  // 修改数据方法
  update(collectionName, json1, json2) {
    return new Promise((resolve, reject) => {
      this.connect().then(db => {
        const result = db.collection(collectionName).updateOne(json1, { $set: json2 }, (err, result) => {
          if (err) {
            reject(err)
          } else {
            resolve(result)
          }
        })
      })
    })
  }

  // 插入数据方法
  insert(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then(db => {
        const result = db.collection(collectionName).insertOne(json, function (err, result) {
          if (err) {
            reject(err)
          } else {
            resolve(result)
          }
        })
      })
    })
  }
}
    // 删除数据方法
    remove(collectionName, json) {
      return new Promise((resolve, reject) => {
        this.connect().then(db => {
          const result = db.collection(collectionName).remove(json, function (err, result) {
            if (err) {
              reject(err)
            } else {
              resolve(result)
            }
          })
        })
      })
    }

module.exports = Db.getInstance()

使用

借助koa框架使用

app.js文件

const koa = require('koa')
const Router = require('koa-router')
const DB = require('./db')
// 实例化
const app = new koa()
const router = new Router()
router.get('/find',async (ctx)=>{
  let res = await DB.find('student',{})
  ctx.body = {
    res: res
  }
})
router.get('/insert',async (ctx)=>{
  let res = await DB.insert("student",{"name":"yuanxiaoshen","age":23,"sex":"男"})
  console.log(res);
  ctx.body = {
    res
  }
})
router.get('/update',async (ctx)=>{
  let res = await DB.update("student",{"name":"yuanxiaoshen"},{"name":"yuanxiaoshen2"})
  console.log(res);
  ctx.body = {
    res
  }
})
router.get('/remove',async (ctx)=>{
  let res = await DB.remove("student",{"name":"yuanxiaoshen2"})
  console.log(res);
  ctx.body = {
    res
  }
})


//启动路由
app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000,res=>{
  console.log('success');
})

个人站点:https://yuanxiaoshen.com

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值