binki
binki

Reputation: 8308

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?

Upvotes: 15

Views: 19975

Answers (4)

ansorensen
ansorensen

Reputation: 1316

You can now use the 'match' property on a String. The match property takes a regex. So you could use something like this:

myfield: {type: String, required: true, match: /^(?!\s*$).+/}

Docs for the String schema, including match: https://mongoosejs.com/docs/api.html#schemastringoptions_SchemaStringOptions-match

Upvotes: 3

Amjed Omar
Amjed Omar

Reputation: 1014

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

Upvotes: 6

Talha Awan
Talha Awan

Reputation: 4619

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

Upvotes: 18

Rupali Pemare
Rupali Pemare

Reputation: 540

The validation will go like

name: {
    type: String,
    validate: {
        validator: function (v) {
            return /^[a-zA-Z]+$/.test(v);
        },
        message: '{PATH} must have letters only!'
    },
},

Try this in model

Upvotes: -1

Related Questions