Reputation: 91193
I am working on a command-line node script that defines a Mongoose model, then creates a new document using that model, then saves it. But the .save(function(){...});
method doesn't seem to finish. It saves the document in Mongo, but the script just sits there and doesn't complete. It never returns back to the command prompt:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
var schema = new mongoose.Schema({
name: String,
street: String
});
var Location = mongoose.model('Location', schema);
var location = new Location({name: "Home", street: "Main Street"});
location.save(function(err){
if (err) {
throw new Error(err);
}
console.log(location);
});
The result is in the terminal is:
{ __v: 0,
name: 'Home',
street: 'Main Street',
_id: 562b062d0ce456a912ee9559 }
But then the terminal just sits there. I have to CTRL+C to get back to the command prompt. Something about the .save()
method seems to make the script hang... The document does get saved in the database though. What am I missing here?
Upvotes: 2
Views: 2333
Reputation: 6153
The database connection is still open and listening for events. For the script to end, you need to close it:
location.save(function(err){
if (err) {
throw new Error(err);
}
console.log(location);
mongoose.connection.close();
});
Upvotes: 5