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

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

问题描述

我在不希望连续运行的脚本中使用猫鼬,而且我面对的似乎是一个非常简单的问题,但我找不到答案.简单地说,一旦我调用将请求发送到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

谢谢

接受以下答案,因为它在技术上是正确的,但是如果有人再次遇到此问题,则当您询问是否还有查询时,似乎猫鼬和/或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.

因此,您可以使用它:如果您希望每个查询都可以正常工作,请确保在调用断开连接()之前已处理了所有查询.

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

推荐答案

您可以使用以下方式关闭连接

You can close the connection with

mongoose.connection.close()

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

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