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

Jus*_*tin 7 mongoose mongodb node.js

假设我在另一个模式(项目)中有一个嵌套的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);
Run Code Online (Sandbox Code Playgroud)

RCh*_*aud 5

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

在您的情况下,您可以执行以下操作:

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