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

时间:2021-07-12 02:34:07

Let's say that I have a nested Schema (invitation) in another schema (item) and when trying to save an invitation object, I want to check if the parent property 'enabled' from the item schema is set to true or false before allowing the person to save the invite object to the invitations array. Obviously, this.enabled doesn't work as it's trying to get it off of the invitationSchema, which doesn't exist. How would one get the 'enabled' property on the parent schema to validate?

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

Any thoughts? Thanks for any help!

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

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 个解决方案

#1


2  

The parent of an embedded document is accessible from an embedded doc model instance by calling instance.parent();. So you can do this from any Mongoose middleware like a validator or a hook.

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

In your case you can do :

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

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

#1


2  

The parent of an embedded document is accessible from an embedded doc model instance by calling instance.parent();. So you can do this from any Mongoose middleware like a validator or a hook.

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

In your case you can do :

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

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