[英]MongoDB: Async function doesn't end on complete or how to close connection properly with mongoose
此问题与 MongoDB 和
mongoose
驱动程序更相关,而不是 async/await 代码本身。
我的*.js
文件中有以下代码:
const model1 = require("../../db/model1");
const model2 = require("../../db/model2");
const {connection} = require('mongoose');
async function f() {
try {
let token = await model2.findById(id) //find just one doc
let cursor = await model1.find({}).limit(5).cursor()
for (let c = await cursor.next(); c != null; c = await cursor.next()) {
//BLAH BLAH BLAH LOGIC
}
} catch (e) {
console.log(e)
}
}
f().then(r => {
connection.close();
console.log('close');
return r
});
所以问题是:
When I am using just one
model
withrequire
(CommonJS) the function ends properly with the following message:Process finished with exit code 0
, but when I add the second model to the file (model2
in my case, but it could be any model文件或另一个 functionrequire
model )然后 function 不会结束。这并不意味着
connection.close()
不起作用,根据 WebStorm 的debug
控制台,来自console.log()
的消息关闭打印成功,但由于某种原因,该过程根本没有结束。 我在其他关于connection.close
的问题上看到过类似这个,但没有一个与我的问题有关。 文档说一个close()
就足够了,它会关闭池中的所有连接。
我导入的每一个 model 都具有以下结构,无一例外:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
require('dotenv').config();
mongoose.connect(`mongodb://${process.env.login}:${process.env.password}@${process.env.hostname}/${process.env.auth_db}`, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
bufferMaxEntries: 0,
retryWrites: true,
useCreateIndex: true,
w: "majority",
family: 4
});
let schema = new mongoose.Schema({
_id: {
type: String
},
any_field: {
type: String,
},
},{
timestamps: true
});
let keys_db = mongoose.model('keys', schema);
module.exports = keys_db;
原因model
代码没有任何setTimeout
或其他 function 除了connect
到 DB 它不应该阻塞线程。 所以我不明白这出了什么问题,我猜 SO 上的某个人已经面临类似的问题,可以为我提供一些澄清。 或者它是异步 function 的正常行为,我不应该看到它有问题?
正如我发现的那样,在每个 model 中使用connect
是一种不好的做法。 不幸的是, mongoose 手册中对它的描述很差。
结果,这是我项目中架构不好的问题。 所以,正确答案如下:
而不是在每个模式/模型文件中使用
connect
,您应该(使用)connect
一次然后导出它或者为每个核心/敏感 function 建立一个单独的连接,例如后端和前端的单独连接,但不是每个 function 的每个连接(就像我一样)
正如我之前提到的,mongoose 文档对这种模式的描述非常差, connection.close()
的文档描述了这种方法,就像你可以一次关闭所有连接一样。 (这实际上是正确的,但在这种情况下它不会帮助你)
我还发现 Stack Overflow 上的这个问题对我的研究非常有用:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.