【问题标题】:Stop mongoose connection that prevent app termination停止阻止应用程序终止的猫鼬连接
【发布时间】:2014-09-03 23:08:19
【问题描述】:

我正在创建一个终端应用程序,它使用 mongoose 进行每次执行的单次插入和读取操作。

我使用以下代码作为我的应用程序的数据库工具

require '../objs/'
mongoose = require 'mongoose'

class DbManager
     constructor: (@dbname="daftar") ->     

    start_connection: ()-> mongoose.connect "mongodb://localhost/#{@dbname}"
    close_connection: ()-> mongoose.disconnect

    getDatabaseName       : ()-> return dbname
    getDatabaseConnection : ()-> return mongoose.connection

    saveNote : (noteObj)->      
        notes_model = mongoose.model "notes", DafNote.schema
        note = new notes_model noteObj
        note.save (err,dt)->
            if err
                console.log err

 # register to node root
 root.DbManager = DbManager

这是调用 db util 的部分

require './src/core/objs/'
require './src/core/data/'

noteObj = new DafNote "test_title","this is a test body"
dbman = new DbManager
dbman.start_connection
dbman.saveNote noteObj
dbman.close_connection

当我运行应用程序时,它会将对象保存到数据库中,但应用程序会一直在终端中等待并且不会关闭。

我已经追踪到问题,我发现mongoose.connect 函数是导致我的应用程序无法关闭的原因,即使我调用了mongoose.disconnect

我真的认为可能是 connectdisconnect 函数的性质异步导致了这个问题。

如何解决这个问题,让应用程序在保存到 mongodb 后关闭,而不是在终端冻结?

【问题讨论】:

    标签: node.js mongodb coffeescript mongoose


    【解决方案1】:

    您确实应该处理事件和回调。 Mongoose 通过.connection 访问器公开连接事件:

    mongoose.connection.on("open",function(err,conn) {
      if (err) throw err;
    
      dbman.saveNote(function(err) {
         // Have your function return the callback and return any error
    
         // Then call disconnect
         mongoose.disconnect(); 
      });
    });
    
    mongoose.connection.on("close",function(err,conn) {
       // Which calls this as the connection is closed
    
       // In case you have something else running
       process.exit(); 
    });
    

    如果您愿意,可以将所有内容封装在您的班级中。但是您确实希望在任务完成时实现回调。

    也不确定除了猫鼬连接之外您还可能运行什么,所以如果您有一个需要关闭调用process.exit() 以及关闭节点事件循环的命令行程序。

    【讨论】:

    • 我不想使用process.exit,而且saveNote 函数不会是唯一的函数,所以我认为使用on 事件会限制代码的模块化。
    • 我想知道如果连接关闭,程序为什么会等待?如果它没有关闭,为什么即使我打电话给mongoose.disconnect它也没有关闭
    • @SamehKamal 真正的意义在于等待您当前的代码似乎没有执行的回调和事件。其次,除非我们可以看到您的所有代码,否则除了发出断开连接之外,可能还有其他原因导致节点没有挂起。上面的代码外壳适用于我们其他已经做了一段时间的人。
    • 问题是连接从来没有关闭过,我已经解决了关闭连接功能设置超时的问题。
    猜你喜欢
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2012-01-13
    相关资源
    最近更新 更多