I have a node.js script that I want to run periodically that writes to mongodb using mongoose. It connects to mongodb, writes, and disconnects. The problem is that the script seems to hang sometimes. I have to manually terminate the script (ctrl+C).
mongoose.connect(MONGODB_URL);
var db = mongoose.connection;
db.on('error', function(err) {
console.log(err);
});
db.on('open', function() {
console.log('opened');
});
db.on('close', function() {
console.log('closed');
});
Model.update(....., function(err) {
if (err) throw err;
mongoose.disconnect();
});
Everything seems to be fine. The script prints opened
and closed
and updates the database correctly, but doesn't terminate after that. I also disconnect inside the callout after all updates to the database are done so there shouldn't be any pending queries that would prevent the script from terminating.
A similar question was asked here: Properly close mongoose's connection once you're done But it doesn't look like there were any true solutions.
EDIT:
I can get it to terminate by adding process.exit()
at the end, but that shouldn't be the case.