CNode

一个mongoose的查询问题

问答
Ssssssskkk发布于10 年前最后回复10 年前7 回复4184 浏览0 收藏

比如 ,点击进入一首歌的介绍详情页,先通过findById找到了这首歌,又通过Id去评论表里找到了歌的评论。 此时如果还想通过分类再找到某一类的歌曲,最后全部render, 要怎么查 ?

查看回复

回复 (7)

J
Jarvin-Guan#1·10 年前

你可以: 看你如何设计而已,原理一样,关联进去

J
Jarvin-Guan#2·10 年前

你的歌曲document里面应该有一个字段是存所有评论的_id,find的时候使用populate自动关联其他document进来就ok了

你需要用到:mongo-auto populate

T
tomoya92#3·10 年前

@Jarvin-Guan 不应该是在评论表里每条评论都会有一个歌曲的id吗?这样才能知道评论的是哪首歌呀!

来自酷炫的 CNodeMD

S
sssssskkk#4·10 年前
引用 Jarvin-Guan你的歌曲document里面应该有一个字段是存所有评论的 id,find的时候使用populate自动关联其他document进来就ok了 你需要用到:mongo auto populate

@Jarvin-Guan 你好,我去看了下它文档,没太看懂,能否举个栗子, 如果是还想找到这首歌所属类型下的所有歌曲呢?

SongSchema.statics = {
findById:function(id,cb){
    return this
        .findOne({_id:id})
        .exec(cb)
}
}

 Song.findById(id,function(err,song){
  Comment
       .find({song:id})
       .populate('from','name')    //评论人name  
       .exec(function(err,comments){
            res.render('detail', {
                title: '详情',
                comments:comments,
                song: song
            })
       });
});
T
tomoya92#6·10 年前

@sssssskkk 都是用populate来关联的,具体怎么写的我给忘了😅

来自酷炫的 CNodeMD

S
sssssskkk#7·10 年前

谢谢大家的解答和提供的思路,捣鼓了一下,可以了。

参见: https://segmentfault.com/a/1190000002727265

参与回复
登录后即可参与回复。登录