企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
~~~ //config.js /* 配置文件 */ module.exports = { dbUrl: "mongodb://localhost:27017/", dbName: 'koa' } ~~~ ~~~ //db.js /* db库 */ const MongoClient = require('mongodb').MongoClient; const { dbUrl, dbName } = require('./config.js'); class Db { static getInstance() { if (!Db.instance) { Db.instance = new Db(); } return Db.instance; } constructor() { /* dbclient定义数据库是否存在 */ this.dbClient = ''; this.connect(); } connect() { return new Promise((resolve, reject) => { /* dbClient数据库不存在,则连接数据库*/ if (!this.dbClient) { MongoClient.connect(dbUrl, { useNewUrlParser: true }, (err, client) => { if (err) { reject(err) } else { let db = client.db(dbName) this.dbClient = db; resolve(this.dbClient) }; }) } else { /* 数据存在,则resolve */ resolve(this.dbClient) } }) } find(collectionName, json) { return new Promise((resolve, reject) => { this.connect().then(db => { var result = db.collection(collectionName).find(json); result.toArray((err, data) => { if (err) reject(err); else resolve(data); }) }) }) } update() { } insert() { } } module.exports = Db.getInstance(); ~~~