'Remove generated string from Mongoose schema with custom validation
I have a schema with a custom validation.
const schema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        validate: {
            validator: /^[a-zA-Z0-9_]{3,16}$/, 
            message: "Usernames must be 3 to 16 characters long and contain only alphanumeric characters and underscores (_)."
        },
    },
    // ...other things
});
However, the validation message comes out like this when I type an invalid username:
User validation failed: username: Usernames must be 3 to 16 characters long and contain only alphanumeric characters and underscores (_).
How do I get rid of the part of the string at the start that says User validation failed: username: ?
Solution 1:[1]
The format is embedded into the ValidationError class. Short of monkey patching that class, I can't see a way to easily change the format.
One option could be to run validation before being thrown by the model:
const user = new User({ username: 'ab' })
const error = user.validateSync()
console.log(error.errors['username'].message)
Or handle ValidationError when caught:
try {
  const user = new User({ username: 'ab' })
  await user.save()
} catch (error) {
  if (error instanceOf mongoose.Document.ValidationError ) {
    console.log(error.errors['username'].message)
  }
}
Solution 2:[2]
To get rid of the initial string , you could simply use a split method on the string returned before displaying it. Here is a sample code:
let stringa = "User validation failed: username: Usernames must be 3 to 16 characters long and contain only alphanumeric characters and underscores (_)."; //replace this with error message
let stringb = (stringa.split(":")[2]);
console.log(stringb);//This displays the needed output string with Usernames 
Solution 3:[3]
Your error object has another nested object called properties that has a field called message.
(example: properties.message) This gives you the exact string you wrote in the mongoose schema
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Matt | 
| Solution 2 | chyke007 | 
| Solution 3 | bguiz | 
