【问题标题】:Properly close mongoose's connection once you're done完成后正确关闭猫鼬的连接
【发布时间】:2012-02-07 11:43:02
【问题描述】:

我在一个不打算连续运行的脚本中使用猫鼬,我面临着一个看似非常简单的问题,但我找不到答案;简单地说,一旦我调用任何向 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() 之前已经处理了每个查询。

【问题讨论】:

  • 有没有办法只通过导入模型来做到这一点?以下答案均无效:\
  • 我无法从问题中看出您是否尝试过,但如果您在等待查询后在异步函数中应用 Kenan 的解决方案,它应该可以工作(即关闭连接)。

标签: node.js mongodb mongoose


【解决方案1】:
mongoose.connection.close(function(){
console.log('Mongoose default connection disconnected through app termination;);
process.exit(0);
});

这将关闭 mongoose 连接,并且还会在您的控制台中通过消息通知您。

【讨论】:

【解决方案2】:

正如 Jake Wilson 所说:您可以将连接设置为变量,然后在完成后断开连接:

let db;
mongoose.connect('mongodb://localhost:27017/somedb').then((dbConnection)=>{
    db = dbConnection;
    afterwards();
});


function afterwards(){

    //do stuff

    db.disconnect();
}

或者如果在异步函数内部:

(async ()=>{
    const db = await mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: 
                  true })

    //do stuff

    db.disconnect()
})

否则当我在我的环境中检查它时会出错。

【讨论】:

    【解决方案3】:

    如果您尝试在方法之外关闭/断开连接,您将收到错误消息。最好的解决方案是在方法的两个回调中关闭连接。虚拟代码在这里。

    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');
    });
    

    【讨论】:

      【解决方案4】:

      你可能有这个:

      const db = mongoose.connect('mongodb://localhost:27017/db');
      
      // Do some stuff
      
      db.disconnect();
      

      但你也可以有这样的东西:

      mongoose.connect('mongodb://localhost:27017/db');
      
      const model = mongoose.model('Model', ModelSchema);
      
      model.find().then(doc => {
        console.log(doc);
      }
      

      你不能调用db.disconnect(),但你可以在使用后关闭连接。

      model.find().then(doc => {
        console.log(doc);
      }).then(() => {
        mongoose.connection.close();
      });
      

      【讨论】:

        【解决方案5】:

        我使用的是 4.4.2 版本,其他答案均不适合我。但是将useMongoClient 添加到选项中并将其放入您调用close 的变量中似乎有效。

        var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })
        
        //do stuff
        
        db.close()
        

        【讨论】:

        • 在 mongoose 5.x 中已弃用
        • 对用户 mongoose.disconnect() 更好
        【解决方案6】:

        您可以将连接设置为变量,然后在完成后断开连接:

        var db = mongoose.connect('mongodb://localhost:27017/somedb');
        
        // Do some stuff
        
        db.disconnect();
        

        【讨论】:

        • 在我的情况下(在 Jest 中测试 Mongoose)这是唯一有效的解决方案
        • 我在 for 循环中使用 Mongoose 执行 Model.update(..)。每次更新后是否需要关闭连接?我的服务器必须处理大量更新并在一段时间后停止工作。
        • 答案与以下相同
        【解决方案7】:

        另一个答案对我不起作用。我必须使用mongoose.disconnect();,如this answer 中所述。

        【讨论】:

        • 这也是拆除测试环境时的首选。
        • mongoose.disconnect() 更好用,也是一种合乎逻辑的方法。
        • 在我使用 Jest 的测试环境中,这可以正确清理所有内容,而在调用 mongoose.connection.close() 时我仍然有打开的句柄。
        【解决方案8】:

        你可以关闭连接

        mongoose.connection.close()
        

        【讨论】:

        • 这实际上关闭了连接。然而,这个调用正在清除我数据库中的内容。当我切换到 mongoose.disconnect() 时,一切正常,我的 mocha 测试又开始正常工作了
        • 这对我有用。我只需要确保我把它放在正确的回调中,否则它可能在保存到数据库之前关闭连接有机会完成。公平地说,我仍在使用一个简单的脚本,它只连接到本地数据库并保存一个简单的示例用户对象。在 user.save() 的回调中,我调用了 mongoose.connection.close()。
        • 如您所见,这些答案已经过时了。如果您使用的是 Mongoose 5.0.4the Connection.close() method 仅导出,仅可用,因此请使用它。
        • @BrianNoah 你是什么意思“这个电话正在清除我数据库中的内容”? mongoose.connection.close()?这种行为有解释吗?这是现在已经修复的猫鼬中的错误,还是..?
        猜你喜欢
        • 2020-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-11
        • 2014-06-20
        • 1970-01-01
        • 1970-01-01
        • 2013-04-22
        相关资源
        最近更新 更多