Search code examples
mongoosemongoose-schema

In mongoose how do I require a String field to not be null or undefined (permitting 0-length string)?


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?


Solution

  • 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 }
        }
    })