我相信你无法为数组中的正确类型的对象定义验证器,只能在字段上定义。如果有一种可以按预期执行此操作的方法,我很乐意撤回我的答案!
然而:
您可以在字段上定义验证器,并像这样访问其中的对象:
const validator = function(theField) {
console.log('The array field', theField);
console.log('The array object', this);
return true;
};
const TextSchema = new Schema({
locale: String,
contexts: [{
field: {
type: String,
validate: validator
},
channel: {
type: String,
validate: validator,
},
}],
});
打印出类似于的内容。
The array field FIELDVALUE
The array object { _id: 5c34a4172a0f34220d17fc1f, field: '21', channel: '2123' }
这样做的缺点是验证器会在数组中的每个字段上运行。如果您只在同一时间设置它们,则可以仅为一个字段设置它。
或者:
如果您不需要定义数组中对象的类型,您可以将数组对象的类型设置为 Mixed 并在此字段上定义一个验证器。
const TextSchema = new Schema({
locale: String,
contexts: [{
type: mongoose.SchemaTypes.Mixed,
validate : function (val) {
console.log(val);
return true;
},
}],
});
还应该打印
{ _id: 5c34a4172a0f34220d17fc1f, field: '21', channel: '2123' }