Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 子文档验证接收文档数组_Mongodb_Mongoose - Fatal编程技术网

Mongodb 子文档验证接收文档数组

Mongodb 子文档验证接收文档数组,mongodb,mongoose,Mongodb,Mongoose,我有一个包含子项(小部件)的父模式(仪表板) 问题是我需要验证单个小部件,但是.pre('save')接收小部件数组 有没有办法验证单个属性?我试图添加widgetSize:{type:String,validate:xxx},但没有成功 var widgetSchema = new Schema({ _id: Schema.Types.ObjectId, measurement: { type: String, required: true }, type: { type: Str

我有一个包含子项(小部件)的父模式(仪表板)

问题是我需要验证单个小部件,但是
.pre('save')
接收小部件数组

有没有办法验证单个属性?我试图添加
widgetSize:{type:String,validate:xxx}
,但没有成功

var widgetSchema = new Schema({
  _id: Schema.Types.ObjectId,
  measurement: { type: String, required: true },
  type: { type: String, required: true },
  key: { type: String, default: '' },
  background: { type: Schema.Types.Mixed, default: false },
  localeId: { type: Schema.Types.Mixed, default: false },
  hintText: String,
  widgetSize: { type: String }
});

widgetSchema.pre('save', function (next) {
  console.log(this);
  if(!sizeValidator(this.widgetSize)) {
    return next(new Error('Size format was incorrect: ' + this.widgetSize));
  }
  next();
});

var dashboardSchema = new Schema({
  slug: { type: String, required: true },
  name: { type: String, required: true },
  backgroundImage: String,
  defaultDashboard: { type: Boolean, default: false },
  backgroundColor: String,
  widgets: [widgetSchema]
});
用于添加子文档的代码

dashboard.widgets.push(widgetToCreate);
return dashboard.saveAsync(); // promisified

看起来您正在使用
this
验证子文档值,正如您所注意到的,该子文档值设置为顶级文档。更直接地说,您可以使用传递给validate函数的值,如下所示:

var widgetSchema = new Schema({
  _id: Schema.Types.ObjectId,
  measurement: {
    type: String,
    required: true
  },
  type: {
    type: String,
    required: true
  },
  key: {
    type: String,
    default: ''
  },
  background: {
    type: Schema.Types.Mixed,
    default: false
  },
  localeId: {
    type: Schema.Types.Mixed,
    default: false
  },
  hintText: String,
  widgetSize: {
    type: String,
    validate: function widgetSizeValidate(val) {
      return val === 'foobar';
    }
  }
});

在Mongo3.2中,将进行验证。也许这会有帮助