javascript - mongoose获取树形结构

 nashiyizhiyu_847_695 发布于 2022-10-25 05:19

结构如下

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()
    })
    2022-10-26 14:19 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有