Model.findById 在我使用 mongoose 时返回 undefined .populate.exec 方法
Model.findById is returning undefined when I use mongoose .populate.exec methods
我正在尝试用它的答案填充我的 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)
时,它returns未定义。当我不填充 Question
模型时,它工作正常并且 foundQuestion
具有所需的值。
代码没有问题。集合名称中存在拼写错误。因此 answers
集合未被填充并返回 null
。更改集合名称后,一切正常。
我正在尝试用它的答案填充我的 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)
时,它returns未定义。当我不填充 Question
模型时,它工作正常并且 foundQuestion
具有所需的值。
代码没有问题。集合名称中存在拼写错误。因此 answers
集合未被填充并返回 null
。更改集合名称后,一切正常。