【问题标题】:Get Parent Schema Property for Validation with Mongoose and MongoDB获取父模式属性以使用 Mongoose 和 MongoDB 进行验证
【发布时间】:2015-09-07 13:54:42
【问题描述】:

假设我在另一个模式(项目)中有一个嵌套模式(邀请),并且在尝试保存邀请对象时,我想检查项目模式中的父属性“启用”是否设置为 true 或 false在允许此人将邀请对象保存到邀请数组之前。显然,this.enabled 不起作用,因为它试图从不存在的invitationSchema 中获取它。如何让父模式上的“启用”属性进行验证?

有什么想法吗?感谢您的帮助!

var validateType = function(v) {
    if (v === 'whateverCheck') {
       return this.enabled || false; <== this doesn't work
    } else {
        return true;
    }
};

var invitationSchema = new Schema({
    name: { type: String },
    type: {
        type: String,
        validate: [validateType, 'error message.']
    }
 });

var itemSchema = new Schema({
    title: { type: String },
    description: { type: String },
    enabled: {type: Boolean}, <== trying to access this here
    invitations: { type: [ invitationSchema ] },
});

var ItemModel = mongoose.model('Item', itemSchema, 'items');
var InvitationModel = mongoose.model('Invitation', invitationSchema);

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    通过调用instance.parent();,可以从嵌入式文档模型实例访问嵌入式文档的父级。因此,您可以从任何 Mongoose 中间件(如验证器或钩子)中执行此操作。

    你可以这样做:

    var validateType = function(v) {
        if (v === 'whateverCheck') {
           return this.parent().enabled || false; // <== this does work
        } else {
            return true;
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 2013-06-06
      • 1970-01-01
      • 2016-12-24
      • 2018-10-09
      • 2018-11-27
      相关资源
      最近更新 更多