nodejs mongoose doesn't return to console after saving an entry
Problem
I use a small piece of code from Console to test saving/retrieving entries in MongoDB database. It looks like this:
var mongoose = require('mongoose');
var models = require('../models');
mongoose.connect('localhost', 'users');
var john = new models.User({ name:'John' });
john.save(function (err, john) {
if (err) {
console.log(err)
}
else {
console.log(john.name);
}
});
After I run it, it shows the name when it saves the entry, then doesn't return me to console and doesn't show any more messages. How can I make it return me to console?
Problem courtesy of: Sergei Basharov
Solution
Your node.js program won't exit as long as a database connection is still open, so you need to close your connection pool after you're done with it like this:
var mongoose = require('mongoose');
var models = require('../models');
mongoose.connect('localhost', 'users');
var john = new models.User({ name:'John' });
john.save(function (err, john) {
if (err) {
console.log(err)
}
else {
console.log(john.name);
}
mongoose.disconnect();
});
Solution courtesy of: JohnnyHK
Discussion
View additional discussion.