0

ドキュメントを保存するときに、次のように事前保存メソッドを定義しました。

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に保存されます。エラーが送信された場合、ドキュメントは保存されるべきではないと思います。ここで何かが足りませんか?

4

2 に答える 2

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();
  });
于 2013-01-07T16:04:41.857 に答える
0

next()を角かっこで囲まないようにすると、フローは続行されます。これを機能させるために、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();
  }

問題が解決しました。

于 2013-01-07T16:04:22.763 に答える