我在pre('validate')挂钩期间执行操作时遇到麻烦。我需要做一些预验证(例如,确保至少填充2个不同字段之一,但不一定要同时填充两个字段)。

const AccessorySchema = new Schema({
    accessory: {
        type: String,
        required: true,
    },
    category: {
        type: String,
        required: true,
        enum: [
            'Offense',
            'Defence',
            'Miscellaneous'
        ]
    },
    space: {
        type: Number,
        required: true,
        validate: {
            validator: Number.isInteger,
            message: 'Space must be an integer'
        }
    },
    priceFixed: {
        type: Number,
        required: false,
        validate: {
            validator: Number.isInteger,
            message: 'Fixed Price must be an integer'
        }
    },
    priceMultiplier: {
        type: [Schema.Types.Mixed],
        required: false
    },
    weightFixed: {
        type: Number,
        required: false,
        validate: {
            validator: Number.isInteger,
            message: 'Fixed Weight must be an integer'
        }
    },
    weightMultiplier: {
        type: [Schema.Types.Mixed],
        required: false
    },
    vehicles: {
        type: [String],
        required: true,
        enum: ["car","cycle"]
    }
});

AccessorySchema.pre('validate', (next) => {
    console.log(this);
    next();
});


然后我将其发送给该对象:

{
    accessory: "some name",
    category: "Miscellaneous",
    priceMultiplier: [3,5],
    weightMultiplier:  [3,5],
    space: 0,
    vehicles: ["car"]
}


这将记录{}并填充mongo DB。但是我无法在预验证中检查任何属性。

猫鼬的版本是^ 4.7.7,nodejs 6.10.2,mongodb的版本是3.2.9

如何访问预验证挂钩中的数据?

最佳答案

不要使用箭头功能,它不会绑定上下文。
将您的代码更改为以下

AccessorySchema.pre('validate', function(next){
    console.log(this);
    next();
});

09-25 18:46