我在不希望连续运行的脚本中使用猫鼬,而且我面对的似乎是一个非常简单的问题,但我找不到答案。简单地说,一旦我调用将请求发送到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(),但没有结果。除此之外,一切都很好(查找,保存,...)。
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
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.
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.
您可以通过以下方式关闭连接