why is mongoose calling my validator with an empty string when my default array is empty?

I believe that the validator is applying the regex to the entire string array as a whole, with an implicit type conversion to a string when applying the regex; an empty array will be implicitly type converted to the empty string "".


A Possible Solution

From my understanding, it appears you are after validating each individual element in the array, as opposed to the entire array value. An array type can be more complexly specified with an element-level validator.

Here is an example of the change:

const Tags = model("tags", new Schema(
    {
        recentTags: {
            type: [{
                type: String,
                validate: tagRegex,
            }],
            default: [],
        },
    },
));

Here are some examples of insertion with this validation:

// valid, uses the default value
await Tags.insertMany([{}]);
// also valid, no elements are here so no validation is done
await Tags.insertMany([{recentTags: []}])
// also valid, the element passes the regex
await Tags.insertMany([{recentTags: ["test"]}])

// not valid, the element does not pass the regex
await Tags.insertMany([{recentTags: [""]}])

See the documentation on array schema types: https://mongoosejs.com/docs/schematypes.html


Side Notes

You might also desire to validate that recentTags is in fact an array or use more complex custom validation error messages.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top