完成后正确关闭猫鼬的连接 [英] Properly close mongoose's connection once you're done

查看:21
本文介绍了完成后正确关闭猫鼬的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个不打算连续运行的脚本中使用猫鼬,我面临着一个看似非常简单的问题,但我找不到答案;简单地说,一旦我调用任何向 mongodb 发送请求的 mongoose 函数,我的 nodejs 实例就永远不会停止,我必须使用 Ctrl+c 或 Program.exit() 手动杀死它.

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().

代码大致如下:

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() 的调用,但没有结果.除此之外,一切正常(查找、保存……).

I tried adding calls to mongoose.disconnect() but no to result. Aside from that, everything works fine (finding, saving, ...).

这与此人完全相同,遗憾的是他没有收到任何答复:https://groups.google.com/group/mongoose-orm/browse_thread/thread/c72cc1c51c76e661

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

谢谢

接受下面的答案,因为它在技术上是正确的,但是如果有人再次遇到这个问题,当您询问是否仍有查询时,mongoose 和/或 mongodb 驱动程序似乎实际上并未关闭连接运行.

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.

所以你有它:确保在调用 disconnect() 之前已经处理了每个查询,如果你想要它实际工作.

So there you have it: make sure that every query has been processed before calling disconnect() if you want it to actually work.

推荐答案

可以用

mongoose.connection.close()

这篇关于完成后正确关闭猫鼬的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆