Search code examples
mongoosemongoose-schema

mongoose match validator giving validation error even though the string matches


I'm trying to use the build-in match validator in mongoose, but it's showing me the following error:

(node:4456) UnhandledPromiseRejectionWarning: ValidationError: data validation failed: phone: Path `phone` is invalid (12345678910).

This is my schema:

const schema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    message: "Name is required",
  },
  isGold: {
    type: Boolean,
    default: false,
  },
  phone: {
    type: String,
    match: /^d{11}$/g,
    required: true,
  },
});

I've checked the regex online (on regex101 website) and it's working fine there, but here it's giving me the error. I've no idea what's causing this problem. Please help.


Solution

  • Are you sure you tested that exact regex? Right now your regex says "start of string", "exactly 11 instances of the letter d", "end of string".

    So, only the string ddddddddddd will ever match.

    Maybe you wanted to match 11 numbers? Then you are missing the backslash in \d!

    The fixed regex looks like this:

    /^\d{11}$/
    

    (Note that the g modifier is superfluous here.)

    On a side note: The fact that you are getting an UnhandledPromiseRejectionWarning indicates that you are not handling your errors correctly. Probably you have some asynchronous code that you are not awaiting (or if you don't use async/await: that you forgot to call .catch() on). This should not happen, and in future versions of node.js it will probably just crash your process, because silent errors are never a good thing, best to fail fast. So, you should figure out where you forgot to handle the promise rejection and fix it.