javascript - mongoose獲取樹形結(jié)構(gòu)
問題描述
結(jié)構(gòu)如下
var LabelSchema = new mongoose.Schema({ name: String, parent: {type: ObjectId, ref: ’Label’, default: null}, children: [{type: ObjectId, ref: ’Label’}]})
希望一次性獲取完整的樹形結(jié)構(gòu)
Label.find({parent: null}) .populate(’children’) .exec(function(err, labels) { if (err) {console.log(err) } // res.send(’test’) res.send({msg: true,result: labels }) })
使用了populate方法,但是只能獲取第一層的childern引用,第二層的childern仍然是objectId;除了自己通過objectId查找對(duì)象,還有沒有其他更簡(jiǎn)便的方法獲取完整樹形結(jié)構(gòu)?
問題解答
回答1:找到解決方法了,在find的時(shí)候先populate
pointSchema.pre(’find’, function(next) { this.populate(’children’) next()})
相關(guān)文章:
1. javascript - immutable配合react提升性能?2. javascript - sublime快鍵鍵問題3. 配置Apache時(shí),添加對(duì)PHP的支持時(shí)語法錯(cuò)誤4. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問?5. css - 寫頁(yè)面遇到個(gè)布局問題,求大佬們幫解答,在線等,急!~6. phpstudy8.1支持win11系統(tǒng)嗎?7. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問8. 實(shí)現(xiàn)bing搜索工具urlAPI提交9. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化10. javascript - 移動(dòng)端上不能實(shí)現(xiàn)拖拽布局嗎?

網(wǎng)公網(wǎng)安備