Here is an isolated example of the problem:
var assert = require('assert')
var mongoose = require('mongoose')
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
mongoose.connect("mongodb://localhost/some_db");
var BlogPostSchema = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = mongoose.model('BlogPost', BlogPostSchema);
var bp = new BlogPost({title: 'blogpost 0'})
bp.save(function(err) {
console.log("this will print 0")
assert.equal(1, 1)
console.log("0 ... no problem")
})
var bp1 = new BlogPost({title: 'blogpost 1'})
bp1.save(function(err) {
console.log("this will print 1")
assert.equal(1, 2)
console.log("this will NOT print")
})
var bp2 = new BlogPost({title: 'blogpost 2'})
bp2.save(function(err) {
console.log("this will print 2")
throw "this error is swallowed"
console.log("this will NOT print")
})
Any error thrown inside the save callback produces no output in the console. The execution seems to pause at that line.
Why does this happen?
Is there a better way to write callbacks, perhaps using a Promise?
You can use connection object error event:
var connection = mongoose.createConnection('mongodb://127.0.0.1/test'),
BlogPost = connection.model('BlogPost', BlogPostSchema);
connection.on("error", function(errorObject){
console.log(errorObject);
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With