search

Home  >  Q&A  >  body text

mongoose get tree structure - Stack Overflow

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?

高洛峰高洛峰2834 days ago805

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-05-02 09:27:52

    Found the solution, populate first when you find it

    pointSchema.pre('find', function(next) {
      this.populate('children')
      next()
    })

    reply
    0
  • Cancelreply