JR Galia
JR Galia

Reputation: 17269

MongoosJS Schema Non-empty String

I have Schema definition below:

var mongoose = require('mongoose');

var CategorySchema = new mongoose.Schema({
    name: {type: String, index: { unique: true }},
    description: String
});

module.exports = mongoose.model('Category', CategorySchema);

How to specify the name will not accept empty string.

Upvotes: 1

Views: 3761

Answers (1)

Martin J.
Martin J.

Reputation: 5118

Setting the field as required will do the trick, like follows:

var CategorySchema = new mongoose.Schema({
    name: {type: String, required: true, index: { unique: true }},
    description: String
});

Another option is to add a validating regular expression, like follows:

var CategorySchema = new mongoose.Schema({
    name: {type: String, validate: /\S+/, index: { unique: true }},
    description: String
});

Upvotes: 5

Related Questions