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?
高洛峰2017-05-02 09:27:52
Found the solution, populate first when you find it
pointSchema.pre('find', function(next) {
this.populate('children')
next()
})