您可以使用mongodb aggregation pipeline 来实现相同的目的。更具体地说,您可以使用$lookup 两次填充parent 及其parent,最后使用$project 来展平结构。
试试这个:
Category.aggregation([{
$lookup : {
from :"categories",
localField : "parent",
foreignField : "_id",
as :"parent"
}
},{
$unwind : "$parent"
},{
$lookup : {
from :"categories",
localField : "parent.parent",
foreignField : "_id",
as :"parent.parent"
}
},{
$unwind : "$parent.parent"
},{
$project : {
l1_id : "$_id",
l1_name : "$name",
l2_id : "$parent._id",
l2_name : "$parent.name" ,
l3_id : "$parent.parent._id",
l2_name : "$parent.parent.name"
}
}]).then(result => {
// result will have l1_id, l1_name, l2_id, l2_name, l3_id, l3_name
// where l2 is the parent,
// and l3 is the parent of parent
}).
注意:$unwind在$lookup阶段之后使用,因为$lookup返回一个数组,我们需要展开它以将其转换为对象。
更多信息请阅读Mongodb $lookup documentation和$project documentation。
希望对你有所帮助。