【发布时间】:2014-02-08 06:30:23
【问题描述】:
我有以下用于表示多对多关系的模式:
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(...)
但是如何从类别方面做到这一点?我知道我可以将 ObjectId ref 数组添加到 CategorySchema 中的 Product 文档中。但是我想避免双向引用(我不想维护它,并且有不一致的风险)。
编辑:这是我实施的解决方案
/**
* 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);
}
};
【问题讨论】:
标签: node.js mongodb mongoose many-to-many schema