Koa封装Mongodb数据库

//DB库
const { MongoClient } = require('mongodb');

const app = {
    dbUrl: "mongodb://localhost:27017/",
    dbName: "book"
}

let client = new MongoClient(Config.dbUrl, { useUnifiedTopology: true });

class Db {

    static getInstance() {   /*1、单例  多次实例化实例不共享的问题*/

        if (!Db.instance) {
            Db.instance = new Db();
        }
        return Db.instance;
    }

    constructor() {

        this.dbClient = ''; /*属性 放db对象*/
        this.connect();   /*实例化的时候就连接数据库*/

    }

    connect() {  /*连接数据库*/
        let _that = this;
        return new Promise((resolve, reject) => {
            if (!_that.dbClient) {         /*1、解决数据库多次连接的问题*/
                client.connect((error) => {
                    if (error) {
                        reject(error)
                        return;
                    }
                    console.log('数据库连接成功!!!');
                    _that.dbClient = client.db(Config.dbName);
                    resolve(_that.dbClient)
                })
            } else {
                resolve(_that.dbClient);
            }

        })

    }

    find(collectionName, json) {

        return new Promise((resolve, reject) => {

            this.connect().then((db) => {

                var result = db.collection(collectionName).find(json);

                result.toArray(function (err, docs) {

                    if (err) {
                        reject(err);
                        return;
                    }
                    resolve(docs);
                })

            })
        })
    }
    update() {

    }
    insert() {


    }
}
//测试查询数据
let myDB = new Db();
myDB.find("users", {}).then((data) => {
    console.log(data)
})

module.exports = Db.getInstance();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值