简体   繁体   English

Mongoose 验证子文档数组

[英]Mongoose validate array of subdocuments

I have the following schema我有以下架构

const TextSchema = new Schema({
  locale: String,
  contexts: [{
    field: String,
    channel: String,
  }],
});

I would like to add a validation to each context that ensures that either field or channel is set.我想为每个上下文添加一个验证,以确保设置了字段或通道。

I have tried extracting the context to a separate schema and setting the validation like below but it only validates the whole array instead of each context.我尝试将上下文提取到单独的模式并设置如下验证,但它只验证整个数组而不是每个上下文。

const TextSchema = new Schema({
  locale: String,
  contexts: {
    type: [ContextSchema],
    validate: validateContext,
  },
});

I believe you can't define a validator for a properly typed object in an array, but only on fields.我相信您不能为数组中正确类型的对象定义验证器,而只能在字段上定义。 If there is a way to do this as expected, I'd be glad to retract my answer!如果有办法按预期执行此操作,我很乐意收回我的答案!

However:然而:

You CAN define a validator on a field and access the object it was in like this:你可以在一个字段上定义一个验证器并像这样访问它所在的对象:

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,
      },
    }],
});

Prints something like打印类似的东西

The array field FIELDVALUE
The array object { _id: 5c34a4172a0f34220d17fc1f, field: '21', channel: '2123' }

This has the disadvantage that the validator runs on every field in the array.这样做的缺点是验证器在数组中的每个字段上运行。 If you only set them at the same time, you could however only set it for one field.如果您只同时设置它们,则只能为一个字段设置。

Alternatively: If you don't need to define the types of the objects in an array however, you can just set the type of the array objects to Mixed and define a validator on this field.或者:如果您不需要定义数组中对象的类型,您只需将数组对象的类型设置为 Mixed 并在此字段上定义一个验证器。

 const TextSchema = new Schema({
    locale: String,
    contexts: [{
      type: mongoose.SchemaTypes.Mixed, 
      validate : function (val) {
       console.log(val);
       return true;
      },
    }],
});

Should also print也应该打印

{ _id: 5c34a4172a0f34220d17fc1f, field: '21', channel: '2123' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM