第一种 aggregate查询
表结构
接口编写
router.get("/get_depart", async (req, res) => { let data = await departModel.aggregate([ { $lookup: { from: "depart", localField: "_id", foreignField: "did", as: "children", pipeline:[ { $lookup: { from: "depart", localField: "_id", foreignField: "did", as: "children", pipeline:[ { $lookup: { from: "depart", localField: "_id", foreignField: "did", as: "children", } } ] } } ] } }, {$match:{level:1}} ]) res.send({ code:200, data }) })
第二种 递归函数
使用时将其中所有的mid
改成你的表自联结字段
即可
router.get('/get_materialfy', async (req, res) => { try { cate = await materialClassfyModel.find().lean(); let d = {} cate.forEach(i => { d[i._id] = i.mid; }) /* 使用递归函数查询三级商品分类的信息 */ function getCate(arr, fid = '') { return arr.filter(item => { if (('mid' in item ? item.mid.toString() : '') === fid.toString()) { // item.fname = fid != '' ? d[fid] : ''; item.children = getCate(arr, item._id); return true; } }) } data = getCate(cate); res.send({ code: 200, data }) } catch (err) { console.log(err) return err } })