node.js 完成后正确关闭猫鼬的连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8813838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Properly close mongoose's connection once you're done
提问by Lepidosteus
I'm using mongoose in a script that is not meant to run continuously, and I'm facing what seems to be a very simple issue yet I can't find an answer; simply put once I make a call to any mongoose function that sends requests to mongodb my nodejs instance never stops and I have to kill it manually with, say, Ctrl+c or Program.exit().
我在一个不打算连续运行的脚本中使用猫鼬,我面临着一个看似非常简单的问题,但我找不到答案;简单地说,一旦我调用任何向 mongodb 发送请求的 mongoose 函数,我的 nodejs 实例就永远不会停止,我必须使用 Ctrl+c 或 Program.exit() 手动杀死它。
The code looks roughly like this:
代码大致如下:
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);
I tried adding calls to mongoose.disconnect() but no to result. Aside from that, everything works fine (finding, saving, ...).
我尝试添加对 mongoose.disconnect() 的调用,但没有结果。除此之外,一切正常(查找、保存……)。
This is the exact same issue as this person, sadly he did not receive any answer: https://groups.google.com/group/mongoose-orm/browse_thread/thread/c72cc1c51c76e661
这是与此人完全相同的问题,遗憾的是他没有收到任何答复:https: //groups.google.com/group/mongoose-orm/browse_thread/thread/c72cc1c51c76e661
Thanks
谢谢
EDIT: accepted the answer below as it is technically correct, but if anyone ever hit this problem again, it seems that mongoose and/or the mongodb driver does not actually close the connection when you ask it to if there are still queries running.
编辑:接受下面的答案,因为它在技术上是正确的,但是如果有人再次遇到这个问题,当您询问是否仍有查询在运行时,mongoose 和/或 mongodb 驱动程序似乎实际上并未关闭连接。
It does not even remember the disconnect call at all, it does not do it once queries are finished running; it just discards your call with no exception thrown or anything of the sort, and never actually close the connection.
它甚至根本不记得断开调用,一旦查询完成运行,它就不会这样做;它只是丢弃你的调用,没有抛出异常或任何类似的东西,并且永远不会真正关闭连接。
So there you have it: make sure that every query has been processed before calling disconnect() if you want it to actually work.
所以你有它:如果你希望它实际工作,请确保在调用 disconnect() 之前已经处理了每个查询。
回答by Kenan
You can close the connection with
您可以关闭连接
mongoose.connection.close()
回答by msrxthr
The other answer didn't work for me. I had to use mongoose.disconnect();as stated in this answer.
另一个答案对我不起作用。我必须mongoose.disconnect();按照这个答案中的说明使用。
回答by Jake Wilson
You can set the connection to a variable then disconnect it when you are done:
您可以将连接设置为变量,然后在完成后断开连接:
var db = mongoose.connect('mongodb://localhost:27017/somedb');
// Do some stuff
db.disconnect();
回答by tumelo
I'm using version 4.4.2 and none of the other answers worked for me. But adding useMongoClientto the options and putting it into a variable that you call closeon seemed to work.
我使用的是 4.4.2 版,其他答案都不适合我。但是添加useMongoClient到选项并将其放入您调用的变量中close似乎有效。
var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })
//do stuff
db.close()
回答by Ramanand Prajapati
You will get an error if you try to close/disconnect outside of the method. The best solution is to close the connection in both callbacks in the method. The dummy code is here.
如果您尝试在方法之外关闭/断开连接,您将收到错误消息。最好的解决方案是在方法的两个回调中关闭连接。虚拟代码在这里。
const newTodo = new Todo({text:'cook dinner'});
newTodo.save().then((docs) => {
console.log('todo saved',docs);
mongoose.connection.close();
},(e) => {
console.log('unable to save');
});
回答by adir abargil
Just as Jake Wilson said: You can set the connection to a variable then disconnect it when you are done:
正如Hyman威尔逊所说:您可以将连接设置为变量,然后在完成后断开连接:
let db;
mongoose.connect('mongodb://localhost:27017/somedb').then((dbConnection)=>{
db = dbConnection;
afterwards();
});
function afterwards(){
//do stuff
db.disconnect();
}
or if inside Async function:
或者如果在 Async 函数中:
(async ()=>{
const db = await mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient:
true })
//do stuff
db.disconnect()
})
otherwise when i was checking it in my environment it has an error.
否则,当我在我的环境中检查它时,它会出错。
回答by Abraham Hernandez
Probably you have this:
可能你有这个:
const db = mongoose.connect('mongodb://localhost:27017/db');
// Do some stuff
db.disconnect();
but you can also have something like this:
但你也可以有这样的东西:
mongoose.connect('mongodb://localhost:27017/db');
const model = mongoose.model('Model', ModelSchema);
model.find().then(doc => {
console.log(doc);
}
you cannot call db.disconnect()but you can close the connection after you use it.
你不能打电话,db.disconnect()但你可以在使用后关闭连接。
model.find().then(doc => {
console.log(doc);
}).then(() => {
mongoose.connection.close();
});

