问题
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.
回答1:
mongoose.connection.close()
works for me but you need to make sure all your db operations have completed before calling it.
回答2:
So I found out what the issue was. I was running this script every 15 minutes as a cron job. It was running on the same server that was running an API we had. There was something else that was running every 15 minutes that would hammer the API with requests. Somehow, this caused problems with the script when connecting and disconnecting from mongodb.
I solved the issue by running the cron job at different times. I don't know if there's anything anyone can do about it to make the mongodb drivers more robust...
来源:https://stackoverflow.com/questions/34098097/mongoose-script-doesnt-terminate-properly