Mongooseasynchronous调用另一个模型使validation不可能

我有两个mongoose模式,看起来像这样:

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'}, }); 

然后将这个模式embedded到如下所示的父模式中:

 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的引用。 如果关联的转换types的'requiresProductAssociation'等于true,我想要做的只是允许将产品添加到stream中。 不幸的是,我使用validation器或中间件,这意味着打电话给mongoose.model('ConversionType'),它是自动asynchronous和混乱的东西了。 做什么?

ps如果有一种方法来存储引用的那个requireProductAssociation布尔值而不是整个对象,这将是伟大的,因为我不需要再对该模型进行asynchronous调用,但我不知道这是可能的。

SchemaType#validate的文档描述了如何对这种情况进行asynchronousvalidation。 asynchronousvalidation器函数接收两个参数,第二个是您调用的asynchronouscallback函数报告该值是否有效。

这可以让你实现这个validation:

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