mongoose get tree structure - Stack Overflow
高洛峰
高洛峰 2017-05-02 09:25:52
0
1
782

The structure is as follows

var LabelSchema = new mongoose.Schema({
  name: String,
  parent: {type: ObjectId, ref: 'Label', default: null},
  children: [{type: ObjectId, ref: 'Label'}]
})

Hope to get the complete tree structure at one time

Label.find({parent: null})
    .populate('children')
    .exec(function(err, labels) {
      if (err) {
        console.log(err)
      }
      // res.send('test')
      res.send({
        msg: true,
        result: labels
      })
    })

The populate method is used, but only the first-level childern reference can be obtained. The second-level childern is still the objectId. In addition to finding the object through the objectId, is there any other easier way to obtain the complete tree structure?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
小葫芦

Found the solution, populate first when you find it

pointSchema.pre('find', function(next) {
  this.populate('children')
  next()
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template