我在保存文档时定义了预保存方法,如下所示:
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();
});
});
此方法检查货币集合以查看是否支持货币字段输入。在测试我的API时,我收到了相应的错误(消息500错误:您选择的货币......),但文档仍保存在MongoDB中。我希望在发送错误时不应保存文档。我在这里错过了什么吗?
答案 0 :(得分:1)
您仍然在错误情况下调用next();
,因此请尝试将该部分重写为:
Currency
.findOne({name: cur})
.select('-_id name')
.exec(function (err, currency) {
if (err) return done(err);
if (!currency) return done(new Error("The currency you selected ('" + currency + "') is not supported. Please select one from /currencies"));
next();
});
答案 1 :(得分:0)
似乎没有将下一个()放在括号中,流程继续。我更改了exec函数,如下所示:
if (err) {
done(err);
} else if (!currency) {
done(new Error("The currency you selected ('" + currency + "') is not supported. Please select one from /currencies"));
} else {
next();
}
问题解决了。