鍍金池/ 問答/數(shù)據(jù)庫/ mongoose查詢子集的子集

mongoose查詢子集的子集

首先,我的mongoose的models如下:

var clubsSchema = new mongoose.Schema({
    "clubCreatetime": String,
    "clubCreater": String,
    "clubName": String,
    "clubDescription": String,
    "clubImage": String,
    "clubMenbers": [String],
    "clubTopics": [{
        "topicCreatetime": String,
        "topicCreater": String,
        "topicTitle": String,
        "topicContent": String,
        "topicComment": [{
            "userId": String,
            "userName": String,
            "commentCreatetime": String,
            "commentContent": String
        }],
        "topicLike": [String],
        "topicState": String
    }],
    "clubState": String
})

然后,我的代碼如下:

let orgId = req.param("orgId");
  let topicId = req.param("topicId");
  Club.findOne({
    _id: orgId
  }, function(clubErr, clubDoc){
    //console.log(clubDoc);
    if(clubErr){
      res.json({
        status: '1',
        msg: clubErr.message,
        result: '查找該社團(tuán)失??!'
      })
    } else {
      clubDoc.clubTopics.findOne({
        _id: topicId
      }, function(topicErr, topicDoc){
        console.log(topicDoc);
        if(topicErr){
          res.json({
            status: '1',
            msg: topicErr.message,
            result: '查找該話題失?。?
          })
        } else {
          res.json({
            status:'0',
            msg: '查找該話題成功!',
            result: topicDoc
          })
        }
      })
    }
  })

在這里,我是想通過路由中的社團(tuán)Id,先找到該社團(tuán);然后在根據(jù)路由中的話題Id,去查詢?cè)撛掝}全部?jī)?nèi)容。但是,它提示我.findOne()這方法不存在,所以想求教下,我要根據(jù)id查詢社團(tuán)下的該話題,要怎么寫呢?謝謝!

目前想到的返回話題信息的方法是:

for(let i=0; i<clubDoc.clubTopics.length; i++){
    if(clubDoc.clubTopics[i]._id==topicId){
        console.log(clubDoc.clubTopics[i]);
    }
}

想問下mongoose有沒有更直接的方法???

回答
編輯回答
玩控

可以給clubTopics建一個(gè)模型,社團(tuán)里存id,ref指向clubTopics這個(gè)集合,查詢的時(shí)候用populate填充
http://mongoosejs.com/docs/po...

2017年1月6日 17:02