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查找對象,還有沒有其他更簡便的方法獲取完整樹形結(jié)構(gòu)?
問題解答
回答1:找到解決方法了,在find的時候先populate
pointSchema.pre(’find’, function(next) { this.populate(’children’) next()})
相關(guān)文章:
1. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題2. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.3. javascript - 請教空白文本節(jié)點的問題4. javascript - 用js實現(xiàn)遠(yuǎn)程js調(diào)用時出現(xiàn)時間機制問題怎樣解決?5. 刷新頁面出現(xiàn)彈框6. javascript - 前端開發(fā) 本地靜態(tài)文件頻繁修改,預(yù)覽時的緩存怎么解決?7. ios - 類似微博首頁,一張圖的時候是如何確定圖大小的?8. java報錯Communications link failure 該如何解決?9. javascript - 怎么看網(wǎng)站用了什么技術(shù)框架?10. PC 手機兼容的 編輯器
