2015-06-22 59 views
5

假设我在另一个模式(项目)中嵌套了模式(邀请),并且在尝试保存邀请对象时,我想检查父属性'enabled'从项目模式设置为true或false,然后允许该人员将邀请对象保存到邀请数组中。很明显,this.enabled不起作用,因为它试图从invitationSchema中取消它,但它不存在。如何获得父架构上的'enabled'属性来验证?使用Mongoose和MongoDB获取父模式属性进行验证

有什么想法?谢谢你的帮助!

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); 

回答

1

可以通过调用instance.parent();从嵌入式文档模型实例访问嵌入式文档的父级。所以你可以从任何Mongoose中间件,比如验证器或钩子来做到这一点。

在你的情况,你可以这样做:

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