使用Mongoose和MongoDB获取验证的父架构属性

时间:2015-06-22 07:42:11

标签: node.js mongodb mongoose

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

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

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 个答案:

答案 0 :(得分:4)

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

在您的情况下,您可以这样做:

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