我使用猫鼬,快递和节点。
我有四个模式:
Step.js
var StepSchema = new mongoose.Schema({ ... });
module.exports = StepSchema;
TC.js
var Step = require('Step');
var TCSchema = new mongoose.Schema({ stepList: [Step] });
module.exports = TCSchema;
TS.js
var TC = require('TC');
var TSSchema = new mongoose.Schema({ tcList: [TC] });
module.exports = TSSchema;
TR.js
var TS = require('TS');
var TRSchema = new mongoose.Schema({ tsList: [TS] });
module.exports = mongoose.model('TR', TRSchema);
示例数据:
{
_id: ObjectId("32d33ddf54de3")
tsList: [
{
_id: ObjectId("66d4f66d44f88")
tcList: [
{
_id: ObjectId("8df84ff8fssdeg")
stepList: [
{
_id: ObjectId("5484kkfci393d")
}
]
}
]
}
]
}
现在,我想使用像这样的id来检索我的tcList:
http://localhost:3000/api/tc/8df84ff8fssdeg
预期的输出是:
{
_id: ObjectId("8df84ff8fssdeg")
stepList: [
{
_id: ObjectId("5484kkfci393d")
}
]
}
我完全不知道如何在这里构建我的猫鼬的
find
。我认为Aggregate
可能有效,但是不确定如何使用Aggregate
。我需要你的帮助。更新资料
我已经按照@hassansin的建议尝试了以下操作,但是在控制台上它会打印出空数组,并且webservice的响应会以没有收到响应的方式进行回复:
var gettcList = function(tcId) {
TR.aggregate(
[
// match by tcList _id and reduce the no of documents for the next pipeline stages
{
$match: {
"tsList.tcList._id": mongoose.Types.ObjectId(tcId)
}
},
// deconstruct tsList array
{
$unwind: "$tsList"
},
// deconstruct tcList array
{
$unwind: "$tsList.tcList"
},
// match again in the deconstructed document list
{
$match: {
"tsList.tcList._id": mongoose.Types.ObjectId(tcId)
}
},
// project the fields
{
$project: {
_id: "$tsList.tcList._id",
stepList: "$tsList.tcList.stepList"
}
}
], function(err, result) {
if (err) {
console.log(err);
return next(err);
}
console.log(result);
return result;
}
);
};
Web服务部分是:
router.get('/tc/:tcid', function(req, res, next) {
res.json(gettcList(req.params.tcid));
});
最佳答案
使用mongodb Aggregation Pipeline:
db.collection.aggregate([
//match by tcList _id and reduce the no of documents for the next pipeline stages
{$match : {'tsList.tcList._id': ObjectId("55bab42fb768129caa039b4b") } },
//deconstruct tsList array
{$unwind: '$tsList'},
//deconstruct tcList array
{$unwind: '$tsList.tcList'},
//match again in the deconstructed document list
{$match : {'tsList.tcList._id': ObjectId("55bab42fb768129caa039b4b") } },
//project the fields
{$project :
{
_id: "$tsList.tcList._id",
stepList : "$tsList.tcList.stepList"
}
}
])