【发布时间】:2021-08-27 10:44:04
【问题描述】:
应该定义架构,因此如果属性 a 设置为 false,则需要属性 b。
const { Schema, model } = require("mongoose");
const schema = new Schema({
a: { type: Boolean, default: false },
b: {
type: Number,
required: function () {
return !this.a;
}
}
});
const Model = model("bla", schema);
Model.validate({a: true});
但如果我像上面那样定义架构,最后一行的验证调用会抛出一个错误,即需要b,即使a 设置为false:
ValidationError: Validation failed: b: Path `b` is required.
他们的问题是,这不是指架构,而是指函数,并且没有定义 a 的值,所以函数只会评估为 true 并且始终需要 b。
【问题讨论】:
标签: node.js mongodb mongoose mongoose-schema