Mongodb Mongoose验证子文档数组
我有以下模式Mongodb Mongoose验证子文档数组,mongodb,validation,mongoose,mongoose-schema,Mongodb,Validation,Mongoose,Mongoose Schema,我有以下模式 const TextSchema = new Schema({ locale: String, contexts: [{ field: String, channel: String, }], }); 我想为每个上下文添加一个验证,以确保设置字段或通道 我尝试将上下文提取到一个单独的模式,并设置如下所示的验证,但它只验证整个数组,而不是每个上下文 const TextSchema = new Schema({ locale: String, c
const TextSchema = new Schema({
locale: String,
contexts: [{
field: String,
channel: String,
}],
});
我想为每个上下文添加一个验证,以确保设置字段或通道
我尝试将上下文提取到一个单独的模式,并设置如下所示的验证,但它只验证整个数组,而不是每个上下文
const TextSchema = new Schema({
locale: String,
contexts: {
type: [ContextSchema],
validate: validateContext,
},
});
我相信您不能为数组中正确类型的对象定义验证器,而只能在字段上定义。如果有一种方法可以像预期的那样做到这一点,我很乐意收回我的答案 然而: 您可以在字段上定义验证器并访问它所在的对象,如下所示:
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' }
这样做的缺点是验证程序在数组中的每个字段上运行。如果只同时设置它们,则只能为一个字段设置
或者:
但是,如果不需要定义数组中对象的类型,则可以将数组对象的类型设置为“混合”,并在此字段上定义验证器
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' }