文章詳情頁
javascript - mongoose獲取樹形結構
瀏覽:269日期:2024-03-29 08:29:46
問題描述
結構如下
var LabelSchema = new mongoose.Schema({ name: String, parent: {type: ObjectId, ref: ’Label’, default: null}, children: [{type: ObjectId, ref: ’Label’}]})
希望一次性獲取完整的樹形結構
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查找對象,還有沒有其他更簡便的方法獲取完整樹形結構?
問題解答
回答1:找到解決方法了,在find的時候先populate
pointSchema.pre(’find’, function(next) { this.populate(’children’) next()})
標簽:
JavaScript
相關文章:
1. html5 - 如何實現帶陰影的不規則容器?2. html5 - 只用CSS如何實現input框的寬度隨框里輸入的內容長短自動適應?3. javascript - 三目運算符的一些問題4. python - uwsgi+django的搭建問題5. css - 移動端字體設置問題6. javascript - ueditor引入報錯問題7. c++ - win7在不刪除管理員密碼的前提下(密碼不為空),如何設置開機不需要密碼?8. html5 - H5 video 問題9. javascript - 移動端上不能實現拖拽布局嗎?10. javascript - 循環嵌套多個promise應該如何實現?
排行榜
