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查找对象,还有没有其他更简便的方法获取完整树形结构?

拉莫斯之舞
浏览 1421回答 1
1回答

慕田峪7331174

在find的时候先populatepointSchema.pre('find', function(next) {  this.populate('children')  next()})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript