2014-01-18 42 views
0

我有一個用來表示一個多一對多的關係下面的模式:貓鼬多對多人口與單向引用

var CategorySchema = new Schema({ 
    title: {type: String},  
}); 
mongoose.model('Category', CategorySchema); 

var ProductSchema = new Schema({ 
    title: {type: String}, 
    categories: [ 
    { 
     type: Schema.ObjectId, 
     ref: 'Category' 
    } 
    ] 
}); 
mongoose.model('Product', ProductSchema); 

當我查詢類別或我想成爲產品能夠得到所有鏈接文件的結果。

查詢產品時,填充類很簡單:

Product.find().populate('categories').exec(...) 

但如何從類別方面做到這一點?我知道我可以在CategorySchema的Product文檔中添加一個ObjectId引用數組。但我想避免雙向參考(我不想維護它,並有不一致的風險)。

編輯:這是我實現

/** 
* List all Categories 
*/ 
exports.all = function (req, res) { 
    //Function needed in order to send the http response only once all 
    //the categories' product has been retrieved and added to the returned JSON document. 
    function sendResponse(categories) { 
    res.json(categories); 
    } 

    AppCategory.list(function (err, categories) { 
    if (err) { 
     errors.serverError(); 
    } else { 
     _.forEach(categories, function (category, index) { 
     category.products = []; 
     Product.byCategory(category._id, function (err, products) { 
      category.products= category.products.concat(products); 
      if (index === categories.length - 1) { 
      sendResponse(categories); 
      } 
     }); 
     }); 
    } 
    }); 
}; 


ProductSchema.statics = { 
    byCategory: function (categoryId, callback) { 
    this.find({'categories': categoryId}) 
     .sort('-title') 
     .exec(callback); 
    } 
}; 

回答

2

你可能不希望做到這一點的解決方案。 :-)我猜想一個產品可能會有一些相當少的類別,但是一個類別可能有成千上萬種產品。在那種情況下,從效率的角度來看,嘗試做Category.populate('products')是不行的。您將使用大量內存,無法以直接方式進行分頁,當產品屬於多個類別時將重複的產品數據加載到內存中等。通過直接查詢產品集合,更好地將產品加載到某個類別中。你可以很容易地通過類別過濾la Product.find({'categories._id': $in: arrayOfCategoryIds}})

+0

感謝您的回答。我實施了像你所描述的東西。我更新了我的問題。現在我可以檢索包含所有產品的類別。在我的用例中,我需要按類別檢索所有產品的列表,並獲取比僅在一個JSON文檔中更好的結果。實際上不會有這麼多的產品,也許最多隻有幾百個。 –