需要Mongoose make Array

ben*_*man 9 validation mongoose

我有一个看起来像这样的猫鼬模型:

var ProjectSchema = new Schema({
    name: { type: String, required: true },
    tags: [{ type: String, required: true }]
});
Run Code Online (Sandbox Code Playgroud)

我希望项目至少有一个标签是必需的.但是当我保存没有标签数组的新项目时,mongoose不会抛出错误:

var project = new Project({'name': 'Some name'});
project.save(function(err, result) {
    // No error here...
});
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?如何指定所需的数组?

小智 19

单行将是:

tags: {type: [String], required: true}

SchemaTypes

  • 对于猫鼬5来说,这个答案不再正确,因为行为已经改变了.请参阅https://github.com/Automattic/mongoose/issues/5139 (5认同)
  • 这对我来说不起作用我尝试资格:{type:[String],required:true}当输入时我没有发送密钥资格蚂蚁它不会抛出任何错误 (3认同)
  • @ManojRana http://jasonjl.me/blog/2014/10/23/adding-validation-for-embedded-objects-in-mongoose/ 你会在这里得到解决方案 (2认同)

rob*_*lep 8

AFAIK,您需要将设置typeArray并添加一个自定义验证器,以确保每个条目都是一个String

tags : {
  type     : Array,
  required : true,
  validate : {
    validator : function(array) {
      return array.every((v) => typeof v === 'string');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)