我正在创建一个终端应用程序,它使用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
功能导致我的应用无法关闭。
我真的认为connect
和disconnect
函数的性质可能是异步导致了这个问题。
如何解决此问题,以便在保存到 mongodb 后关闭应用程序,而不是在终端冻结?
答案 0 :(得分:0)
你真的应该处理事件和回调。 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();
});
如果需要,可以封装您班级中的所有内容。但是你确实希望在任务完成时实现回调。
除了mongoose连接之外,还不确定你还在运行什么,所以如果你有一个命令行程序需要关闭调用process.exit()
以及关闭节点事件循环。