Scott Switzer
Scott Switzer

Reputation: 1074

Mongoose still saves a document when there is an error

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?

Upvotes: 0

Views: 65

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311855

You're still calling next(); in the error case, so try rewriting that part as:

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();
  });

Upvotes: 1

Scott Switzer
Scott Switzer

Reputation: 1074

Seems like by not putting the next() in brackets, the flow continues. I changed the exec function as follows in order for this to work:

  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();
  }

Problem solved.

Upvotes: 0

Related Questions