2016-07-15 51 views
0

考虑:的Node.js - 填充嵌入文档中猫鼬

var productSchema = new Schema({ 
    name: String, 
    details : [{ name: String, description: String }] 
}) 


var listSchema = new Schema({ 
    name: String, 
    products: [{ 
    product_id: { type: Schema.Types.ObjectId, ref: 'Product' }, 
    product_vid: { type: Schema.Types.ObjectId, ref: 'Product.details' } 
    }] 
}) 

我该怎么办的列表查询,只有一个细节,它匹配product_vid相应的product_id?

List.findById(list_id) 
    .populate({ 
     path: 'products.product_id', 
     populate: { 
     path: 'products.product_vid' 
     } 
    }) 
    .exec(function(err, doc){ 
     ...... 
} 

回答

0

这是错误的

product_vid: { type: Schema.Types.ObjectId, ref: 'Product.details' } 

细节是模型的领域。而不是自我模型。

它应该是这样的..

var listSchema = new Schema({ 
    name: String, 
    products: [{ type: Schema.Types.ObjectId, ref: 'Product' }], 
}) 

然后

populate('products') 

或可能

populate('products products.details') 

只要尝试,让我知道。

+0

它不工作......我以前试过。它显示错误说:“架构尚未注册模型product.details” – tellingeric

+0

您的意思是product.detail或products.product_id?好的..我想这是错误的。 product_vid:{type:Schema.Types.ObjectId,ref:'Product.details'} – enRaiser

+0

但是如何获得正确版本的细节?我只想得到正确的产品和正确的细节..(这就是为什么我把一个product_vid放入列表中的产品数组中) – tellingeric

3

没有必要

product_vid: { 
type: Schema.Types.ObjectId, ref: 'Product.details'} 
在listSchema

var productSchema = new Schema({ 
name: String, 
details : [{ name: String, description: String }] 
    }) 


var listSchema = new Schema({ 
    name: String, 
    products: [{ type: Schema.Types.ObjectId, ref: 'Product' }]) 

     List.findById(list_id) 
     .populate({ 
       path: 'products', 
       match: { details: "your matching value"}) 
      .exec(function(err, doc){ 
        ...... 
     } 
+0

如果我删除了product_vid,那我该如何使用相应的细节填充产品?像匹配值是_id的详细信息,我需要找到一种方法将它存储在列表中的某个地方? – tellingeric

+0

您将返回整个数组,而不仅仅是导致匹配的数组元素。 –