当我使用猫鼬.populate.exec方法时,Model.findById返回未定义

时间:2020-04-20 09:02:26

标签: mongoose mongoose-populate

我试图用其答案填充我的Question模型,并使用其ID找到社区,如下所示:

router.get('/communities/:type/:id_community/:id_question' , (req , res)=>{
    console.log(req.params.id_question);
    PublicCommunity.findById(req.params.id_community , (err , foundCommunity)=>{
        if(err){
            console.log(err)
            res.redirect('back');
        }else{
            Question.findById(req.params.id_question).populate('answers').exec ((err2 , foundQuestion)=>{
                console.log(foundQuestion);
                seedAnswer(foundQuestion);
                if(err2){
                    console.log('err here');
                    console.log(err);
                    res.redirect('back');
                }else{

                    res.render('../views/publicCommunity/questions/show' , {type:req.params.type  ,question: foundQuestion , community: foundCommunity});
                }
            });
        }
    });
});

问题模式为:

let questionSchema = new mongoose.Schema ({
    title: String,
    text : String,
    comments:[{
        type : mongoose.Schema.Types.ObjectId,
        ref  : 'Comment'
    }],
    answers: [{
        type: mongoose.Schema.Types.ObjectId,
        ref:'Answer'
    }],
    date: {type: Date , default: Date.now},
    author: String
});

当我console.log(foundQuestion)时,它返回未定义。当我不填充Question模型时,它可以正常工作,并且foundQuestion具有所需的值。

1 个答案:

答案 0 :(得分:-1)

代码没有错。集合名称中存在拼写错误。因此,answers集合没有被填充,并且正在返回null。更改收藏名称后,一切正常。