In a schema for a collection I have in Mongoose, I have a string value required like so for a particular model:
preExecutionText: { type: String, required: true }
However, if I try to store an empty string for this property, I get this error:
'nodeData.29.preExecutionText': ValidatorError: Path 'preExecutionText' is required.
I figure that setting required to true for this property means that I can't store empty strings. Is there a way to configure this so that only null values aren't allowed, and empty strings are?
CodePudding user response:
For the empty string, you can use a if statement to check is the 'required' value is true and if it's a empty string. In other words, you have to first check if the 'required' value is true and if it's null.
Code exmaple:
if (foo.bar.required && foo.bar.type === null || foo.bar.type === "") {
console.log("Error!");
} else {
if (foo.bar.type === "") {
// Write to database
} else {
console.log("Error!");
}
}
Hope this helps!!
CodePudding user response:
Yes, you can use the minlength property to specify that the string must have at least one character. For example:
preExecutionText: {
type: String,
required: true,
minlength: 1
}
This will require that the preExecutionText property is not empty, but will allow you to store empty strings. You can also use the maxlength property to set an upper limit on the number of characters allowed in the string.