I have tried this, which allows null
, undefined
, and complete omission of the key to be saved:
{
myField: {
type: String,
validate: value => typeof value === 'string',
},
}
and this, which does not allow ''
(the empty string) to be saved:
{
myField: {
type: String,
required: true,
},
}
How do I enforce that a field is a String
and present and neither null
nor undefined
in Mongoose without disallowing the empty string?
If you add { type: String, trim: true } to a field in your schema, then trying to save strings like " hello" , or "hello " , or " hello " , would end up being saved as "hello" in Mongo - i.e. white spaces will be removed from both sides of the string.
mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.
You can think of a Mongoose schema as the configuration object for a Mongoose model. A SchemaType is then a configuration object for an individual property. A SchemaType says what type a given path should have, whether it has any getters/setters, and what values are valid for that path.
Just write this once, and it will be applied to all schemas
mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');
See this method in official mongoose documentation & github issue
By making the required field conditional, this can be achieved:
const mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
myField: {
type: String,
required: isMyFieldRequired,
}
});
function isMyFieldRequired () {
return typeof this.myField === 'string'? false : true
}
var User = mongoose.model('user', userSchema);
With this, new User({})
and new User({myField: null})
will throw error. But the empty string will work:
var user = new User({
myField: ''
});
user.save(function(err, u){
if(err){
console.log(err)
}
else{
console.log(u) //doc saved! { __v: 0, myField: '', _id: 5931c8fa57ff1f177b9dc23f }
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With