//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();
Koa封装Mongodb数据库
最新推荐文章于 2023-03-16 11:35:16 发布