Javascript 如何解决我的数据库连接问题,并要求?
我有一个使用Express generator创建的Express应用程序。我有一个导出应用程序的标准Javascript 如何解决我的数据库连接问题,并要求?,javascript,node.js,express,Javascript,Node.js,Express,我有一个使用Express generator创建的Express应用程序。我有一个导出应用程序的标准app.js文件。我还有一个标准的www文件,用于导入app,是应用程序的起点: const app = require('../app') const debug = require('debug')('img-final:server') const http = require('http') const Mongo = require('../utils/dbConnection/dbC
app.js
文件。我还有一个标准的www
文件,用于导入app
,是应用程序的起点:
const app = require('../app')
const debug = require('debug')('img-final:server')
const http = require('http')
const Mongo = require('../utils/dbConnection/dbConnection')
const port = normalizePort(process.env.PORT || '3000')
app.set('port', port)
/**
* Create HTTP server.
*/
const server = http.createServer(app)
/**
* Listen on provided port, on all network interfaces.
*/
async function startServer() {
try {
await Mongo.init()
debug('Connected correctly to DB')
server.listen(port)
} catch (err) {
debug(err)
}
}
startServer()
//some more unrelated code.
我还有一个用于连接dbdbConnection.js的实用程序文件:
const MongoClient = require('mongodb').MongoClient
class Mongo {
async init() {
const client = new MongoClient(`mongodb://localhost:27017/img-new`, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
await client.connect()
this.db = client.db('img-new')
}
getConnection() {
return this.db
}
}
module.exports = new Mongo()
我的问题是,当我启动我的应用程序时,const-app=require('../app')
显然是首先运行的,无论在我的应用程序路由控制器中的什么地方,我使用getConnection()
,连接都是未定义的,因为我的Mongo.init()
是在const-app=require('../app')
之后运行的
我正试图理解如何以理智的方式解决这个问题。我想我可以将所有require
和startServer
中的所有其他代码移动到wait Mongo.init()之后,但似乎应该有更好的解决方案。多谢各位
编辑:
这是一个好的解决方案吗
const debug = require('debug')('img-final:server')
const http = require('http')
const Mongo = require('../utils/dbConnection/dbConnection')
async function startServer() {
try {
await Mongo.init()
const app = require('../app')
const port = normalizePort(process.env.PORT || '3000')
app.set('port', port)
const server = http.createServer(app)
server.listen(port)
} catch (err) {
debug(err)
}
}
startServer()
我有一个解决方案,但我不确定它是否满足您的期望
在getConenction
方法中,检查this.db
是否为undefined
。如果是这种情况,只需调用init()方法,然后返回this.db
。如果不是,则直接返回this.db
。
代码如下所示:
async getConnection() {
if(!this.db) {
// connection to db is not established yet, we call `init` method
await this.init();
}
// this.db is defined here, we return the connection
return this.db;
}
您不必在startServer()
函数中调用wait Mongo.init()
吴克钦之前的回答是正确的。我添加了一些防御性编码,以防止同时调用多个this.init()
。注意:我在连接时没有针对错误编写代码
const MongoClient = require('mongodb').MongoClient
class Mongo {
init() {
// Gerard we set isConnected to a promise
this.isConnected = new Promise(async (resolve, reject) => {
const client = new MongoClient(`mongodb://localhost:27017/img-new`, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
await client.connect()
this.db = client.db('img-new')
resolve();
});
}
isConnected = null;
async getConnection() {
if(this.isConnected === null) {
// connection to db is not established yet, we call `init` method
this.init();
}
// Now either the DB is already connected, or a connection is in progress. We wait.
await this.isConnected;
// this.db is defined here, we return the connection
return this.db;
}
}
module.exports = new Mongo()
然后打电话的人就可以了
connection = await Mongo.getConnection();
我总是用猫鼬。它很好地解决了这个问题,文档也很好。我注意到getConnection()
变为异步,因此调用此函数的代码受到影响。这是一种有趣的方法,但是问题是,当您从async
函数返回某些内容时,您得到了一个承诺。你需要等待它以后,它会导致一些其他问题。例如,我不能在另一个类的构造函数中等待我的DB连接。您必须等待,因为在一般情况下,您不知道连接到DB需要多长时间。如果您假设在第一次创建getConnection()之前就连接了数据库,这将导致各种难以检测的问题。如果我说服了你,那么你应该使用@ĐăngKhoaĐinh的代码,但你也应该检查连接是否也在进行中。如果不这样做,可能会调用多个this.init()
。