我有三种型号:产品,类别和事件,
这些是我的模特
product.js
var ProductSchema = new mongoose.Schema({
p_id: Number,
p_name: String,
p_fk_category: {type: mongoose.Schema.Types.ObjectId, ref: 'categories'},
}
, {collection: 'products'});
module.exports = mongoose.model('products', ProductSchema);
Category.js
var CategorySchema = new mongoose.Schema({
c_id: Number,
c_name: String,
c_fk_event: {type: mongoose.Schema.Types.ObjectId, ref: 'events'},
}
, {collection: 'categories'});
module.exports = mongoose.model('categories', CategorySchema);
Event.js
var EventSchema = new mongoose.Schema({
e_id: Number,
e_name: String,
e_fk_club_id: Number,
}
, {collection: 'events'});
module.exports = mongoose.model('events', EventSchema);
假设我有:3个产品,2个类别和2个事件
产品1和产品3属于第1类
产品2属于第2类
第1类属于事件1
第2类属于事件2
第1项赛事有club_id 1111
第2项赛事有club_id 2222
这是一个例子 的产品
{
"p_id": 001,
"p_name": "Product 1",
"p_fk_category": ObjectId("584fcfa4c50c7ab8ac31ba9f")
}
{
"p_id": 002,
"p_name": "Product 2",
"p_fk_category": ObjectId("584fcfa4c50c7ab8ac31baa0")
}
{
"p_id": 003,
"p_name": "Product 3",
"p_fk_category": ObjectId("584fcfa4c50c7ab8ac31ba9f")
}
分类
{
"c_id": ObjectId("584fcfa4c50c7ab8ac31ba9f"),
"c_name": "Category 1",
"c_fk_event": ObjectId("584592bcf9fec37548e19485")
}
{
"c_id": ObjectId("584fcfa4c50c7ab8ac31baa0"),
"c_name": "Category 2",
"c_fk_event": ObjectId("584592bcf9fec37548e19486")
}
事件
{
"e_id": ObjectId("584592bcf9fec37548e19485"),
"e_name": "event 1",
"e_fk_club_id": 1111
}
{
"e_id": ObjectId("584592bcf9fec37548e19486"),
"e_name": "event 2",
"e_fk_club_id": 2222
}
问题是:在mongoose中,如何从e_fk_club_id获取等于1111的产品,换句话说,如何获得产品1和产品3,其类别属于事件1,其club_id等于1111。
我尝试了一个深度填充的例子,但它没有工作。
提前致谢
答案 0 :(得分:1)
当我遇到您的问题时,您可以使用$ lookup聚合查询。我写了一个查询给你检查:
db.events.aggregate([{"$match":{"e_fk_club_id":1111}},{"$lookup":{"from":"categories","localField":"e_id","foreignField":"c_fk_event","as":"categories"}},{"$unwind":"$categories"},{"$lookup":{"from":"products","localField":"categories.c_id","foreignField":"p_fk_category","as":"products"}}]).pretty()