I have a pre-save method defined when saving a document, as follows:
Org.pre("save",function(next, done) {
var Currency = require('./currency');
var cur = this.get('currency');
console.log("checking currency: " + cur);
Currency
.findOne({name: cur})
.select('-_id name')
.exec(function (err, currency) {
if (err) done(err);
if (!currency) done(new Error("The currency you selected ('" + currency + "') is not supported. Please select one from /currencies"));
next();
});
});
This method checks the currencies collection to see if the currency field input is supported. In testing my API, I get the appropriate error returned (500 error with the message: The currency you selected…), but the document is still saved in MongoDB. I would expect that when an error is sent the document should not be saved. Am I missing something here?
You’re still calling
next();in the error case, so try rewriting that part as: