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. mysql - 10g數(shù)據(jù)庫如何遷移2. php - 有關(guān)sql語句反向LIKE的處理3. 在視圖里面寫php原生標簽不是要迫不得已的情況才寫嗎4. 獲取上次登錄ip的原理是啥?5. node.js - session怎么存到cookie,然后服務(wù)器重啟后還能獲取。數(shù)據(jù)庫不用mongodb或redis,數(shù)據(jù)庫是mysql6. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時間會消失是什么情況?7. 為什么說非對象調(diào)用成員函數(shù)fetch()8. fetch_field_direct()報錯9. 為什么點擊登陸沒反應(yīng)10. mysql多表聯(lián)合查詢優(yōu)化的問題
