Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 698
binki Avatar asked Jun 02 '17 04:06

binki


People also ask

What is trim true in Mongoose schema?

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.

What does Mongoose unique validator do?

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.

What is schema path Mongoose?

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.


2 Answers

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

like image 52
Amjed Omar Avatar answered Dec 25 '22 23:12

Amjed Omar


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 }
    }
})
like image 45
Talha Awan Avatar answered Dec 26 '22 00:12

Talha Awan