I'm creating an a terminal application that uses mongoose for single insert and read operation per execution.
I use the following code as a database util for my app
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
And this is the part calling that 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
And when I run the application it saves the object to the database but the application keeps waiting in terminal and don't close.
I've traced the problem, and I've thatmongoose.connect
function is the reason causing my app not to close even if I've called mongoose.disconnect
.
I really think that it may be the nature of the connect
and disconnect
function being asynchronous is causing that problem.
How can I solve this problem to make the application close after saving to mongodb and not to freeze at terminal?