文章详情页
javascript - mongoose获取树形结构
问题描述
结构如下
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. python相关问题求解决,有偿2. javascript - input输入框触发change事件后,外部元素会被选中3. python - 用__call__ 实现装饰器功能4. javascript - 把字符串日期转换成一般时间格式后,发现小于10的数字不会自动添加0在前面,如下5. javascript - 在sublime中如何给.vue文件注释?6. javascript - js判断一个数组是否重复7. python - 请问用cxfreeze打包的可执行程序能反编译出源码么?8. javascript - vue2.0中router.repalce跟router.push有什么区别,二者的应用场景是会有怎样的区别?9. javascript - 这种上传图片预览怎么做?10. javascript - prismplayer播放器全屏问题
排行榜