MongoosJS Schema非空字符串

时间:2013-06-27 09:35:53

标签: mongodb mongoose

我在下面有Schema定义:

var mongoose = require('mongoose');

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

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

如何指定name将不接受空字符串。

1 个答案:

答案 0 :(得分:4)

将字段设置为 required 将起到作用,如下所示:

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

另一种选择是添加一个验证正则表达式,如下所示:

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