Skip to content

Instantly share code, notes, and snippets.

@andrsnn
Created August 28, 2017 21:24
Show Gist options
  • Save andrsnn/938c6e72cf1f51493dc18bcecc90f8a9 to your computer and use it in GitHub Desktop.
Save andrsnn/938c6e72cf1f51493dc18bcecc90f8a9 to your computer and use it in GitHub Desktop.
Reproducing mongoose post init error handling
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var uri = 'mongodb://localhost:27017/development';
mongoose.connect(uri, function (err) {
if (err) throw new Error(err);
console.log(`Connected to ${uri}`);
var TestSchema = new Schema();
TestSchema.post('init', function (model, next) {
return next(new Error(`Failure ${model._id}`));
});
var TestModel = mongoose.model('Test', TestSchema);
var modelsToSave = [];
for (var i = 0; i < 10; i++) {
modelsToSave.push(new TestModel());
}
Promise.all(modelsToSave.map(model => model.save()))
.then(() => {
var i = 0;
TestModel.find({},
// called multiple times
function (err) {
console.log(`called ${++i} times`, err);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment