2016-07-15 53 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

您將返回整個數組,而不僅僅是導致匹配的數組元素。 –