对另一个模型的猫鼬异步调用使验证变得不可能

Mongoose async call to another model makes validation impossible

我有两个猫鼬模式,如下所示:

var FlowsSchema = new Schema({
    name: {type: String, required: true},
    description: {type: String},
    active: {type: Boolean, default: false},
    product: {type: Schema.ObjectId, ref: 'ClientProduct'},
    type: {type: Schema.ObjectId, ref: 'ConversionType'},
});

此模式随后嵌入到如下所示的父模式中:

var ClientCampaignSchema = new Schema({
    name: {type: String, required: true},
    description: {type: String},
    active: {type: Boolean, default: false},
    activeFrom: {type: Date},
    activeUntil: {type: Date},
    client: {type: Schema.ObjectId, ref: 'Client', required: true},
    flows: [FlowsSchema]
});

var ConversionTypeSchema = new Schema({
    name: {type: Schema.Types.Mixed, required: true},
    requiresProductAssociation: {type: Boolean, default: false}
});

如您所见,我的 FlowsSchema 包含对 ConversionType 的引用。如果关联的转换类型 'requiresProductAssociation' 等于 true,我想做的只是允许将产品添加到流程中。 不幸的是,无论我使用验证器还是中间件,这都意味着调用 mongoose.model('ConversionType') 会自动异步并把事情搞砸。做什么?

p.s。如果有一种方法可以存储对 requiresProductAssociation 布尔值而不是整个对象的引用,那会很棒,因为我不再需要对该模型进行异步调用,但我不知道这是否可能。

SchemaType#validate 的文档描述了如何对此类情况执行异步验证。异步验证器函数接收 两个 个参数,第二个是您调用的回调函数,用于异步报告值是否有效。

这让您可以将此验证实现为:

FlowsSchema.path('type').validate(function(value, respond) {
    mongoose.model('ConversionType').findById(value, function(err, doc) {
        respond(doc && doc.requiresProductAssociation);
    });
});