具有某些必需属性的猫鼬混合模式

时间:2019-03-21 20:43:23

标签: node.js mongodb mongoose

我正在尝试定义一个猫鼬模式,其中我有一个混合类型,但想要在仍允许任何内容的同时提供一些必需的属性。这可能吗?

new Schema({
  myProperty: {
    name: {
      type: String,
      required: true,
    }
    <anything else>    
  }
})

我发现的唯一伪解决方案是定义可以混合类型的属性级别,但我想避免这种情况:

new Schema({
  myProperty: {
    name: {
      type: String,
      required: true,
    }
    additionalData: Object,    
  }
})

1 个答案:

答案 0 :(得分:0)

您可以将验证器用于混合:

您的架构将是:

const UserSchema = new Schema({
  myProperty: {
    type: mongoose.Schema.Types.Mixed    
  }
})

还有您的验证人:

UserSchema.path('myProperty').validate(function (value) {
  return value && value.name !== undefined && typeof value.name === "string";
}, 'name is a required string');

然后,如果您尝试使用:

const User = mongoose.model('User', UserSchema);

let u = new User({ myProperty: {name: "bar" }})
console.log(u.validateSync())
// undefined => validation passed

u = new User({ myProperty: {foo: "bar" }})
console.log(u.validateSync())
// { ValidationError: User validation failed: myProperty: name is a required string
相关问题