我在一个不打算连续运行的脚本中使用 Mongoose ,我正面临一个看似非常简单的问题,但我找不到答案;简单地说,一旦我调用任何向 mongodb 发送请求的 mongoose 函数,我的 nodejs 实例就永远不会停止,我必须使用 Ctrl+c 或 Program.exit() 手动杀死它。
代码大致如下:
var mongoose = require('mongoose');
// if my program ends after this line, it shuts down as expected, my guess is that the connection is not really done here but only on the first real request ?
mongoose.connect('mongodb://localhost:27017/somedb');
// define some models
// if I include this line for example, node never stop afterwards
var MyModel = mongoose.model('MyModel', MySchema);
我尝试添加对 mongoose.disconnect() 的调用,但没有结果。除此之外,一切正常(查找、保存……)。
这与此人完全相同,遗憾的是他没有收到任何答案:https://groups.google.com/group/mongoose-orm/browse_thread/thread/c72cc1c51c76e661
谢谢
编辑:接受下面的答案,因为它在技术上是正确的,但是如果有人再次遇到这个问题,当您询问是否仍有查询时,似乎 mongoose 和/或 mongodb 驱动程序实际上并没有关闭连接正在运行。
它甚至根本不记得断开连接调用,一旦查询完成运行它就不会这样做;它只是丢弃你的调用,不会抛出任何异常或任何类似的东西,并且永远不会真正关闭连接。
所以你有它:如果你希望它实际工作,请确保在调用 disconnect() 之前已经处理了每个查询。
最佳答案
你可以关闭连接
mongoose.connection.close()
https://stackoverflow.com/questions/8813838/