How to validate mongoose document by current field in existed doc in mongodb?

Viewed 43

I have mongoose schema

const messageSchema = new mongoose.Schema({{
  name: String,
  code: String //enum ['start', 'waiting', 'complete']
})

for example - I will save an item:

{
  name: 'firstItem',
  code: 'start'
}

next time - when update this document I want to use validation function

function validateCode(value) {
   if (existed.code === 'start' && value === 'waiting') {
      return true;
   }

   if (existed.code === 'waiting' && value === 'complete') {
      return true;
   }

   return false;
}

but How can I call existed item id db in validate function? Big thx!

1 Answers

I'm fairly certain that validators don't get access to the object that is being updated, so what you are trying to do won't work with validators.
There are however different options for you. For instance you could use a instance method.
For the validation flow you described before, a instance method accomplishing the same would be this:

messageSchema.methods.updateCode = function(value){
  const fromStart = this.code === 'start' && value === 'waiting';
  const fromWaiting = this.code === 'waiting' && value === 'complete';
  if (fromStart || fromWaiting) {
    this.code = value;
    return this.save();
  } 
  else {
    throw Error("Invalid code update");
  }
}

With this method you would also be free to choose a more optimized way to handle the "invalid code update" case.
More on instance methods could be found in the mongoose docs

Related