In mongoose how do I require a String field to not be null or undefined (permitting 0-length string)?
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 }
}
})