javascript - mongoose取得樹狀結構
高洛峰
高洛峰 2017-05-02 09:25:52
0
1
720

結構如下

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查找對象,還有沒有其他更簡便的方法獲取完整樹形結構?

高洛峰
高洛峰

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

全部回覆(1)
小葫芦

找到解決方法了,在find的時候先populate

pointSchema.pre('find', function(next) {
  this.populate('children')
  next()
})
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!