mongodb - Mongoose 验证子文档数组

标签 mongodb validation mongoose mongoose-schema

我有以下架构

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

我想为每个上下文添加一个验证,以确保设置了字段或 channel 。

我试过将上下文提取到单独的模式并像下面这样设置验证,但它只验证整个数组而不是每个上下文。

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' }

这有一个缺点,即验证器在数组中的每个字段上运行。如果您只同时设置它们,则只能为一个字段设置。

或者: 但是,如果您不需要定义数组中对象的类型,则只需将数组对象的类型设置为 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' }

关于mongodb - Mongoose 验证子文档数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54092094/

相关文章:

windows - 使用 Microsoft VC (cl.exe) 2010 (10.0) Express 和 ActivePerl 5.12.4/32 构建 Perl/C 模块

mongodb - 如何使用 pymongo 创建索引

php - Laravel 5.5 在验证请求文件中使用自定义验证规则?

python - 在 FormEncode 验证失败后使用查询字符串参数重新呈现 Pylons 表单

在 Mongoose 中将属性定义为 ObjectId 时出现 typescript 错误

node.js - Mongodb:我可以比较一个字段中的值是否包含在另一个字段中吗

javascript - Node :-How to store image from a form in mongo DB using multer and send the same image to mail as an attachment

javascript - 如何使用 Meteor 监视服务器对集合的更改?

javascript - Element-UI el-select 验证

node.js - 如何在更新期间检查该数据是否已存在于数据库中(Mongoose And Express)