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