您的位置:首页技术文章
文章详情页

javascript - mongoose获取树形结构

【字号: 日期:2024-03-29 08:29:46浏览:139作者:猪猪

问题描述

结构如下

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
相关文章: