[英]Mongoose populate is not working, returns undefined
app.get("/index/:id", function(req, res)
{
campgrounds.findById({ _id: req.params.id }).populate("comment").exec(
function(error, foundscamp) {
console.log(foundscamp);
if (error) {
consol.log(error);
console.log("you gotcha error");
} else {
//render the show page with sopecific id
res.render("show.ejs", { foundcamps: foundscamp });
}
});
});
如果我们看一下关于mongoosejs文档findById :
Model.findById()
通过其
_id
字段查找单个文档。findById(id)
几乎*等同于findOne({ _id: id })
。 如果findById()
文档的_id
查询,请使用findById()
而不是findOne()
。
- 除了如何处理未定义。 如果使用
findOne()
,则会看到findOne(undefined)
和findOne({ _id: undefined })
等同于findOne({})
并返回任意文档。 但是,猫鼬findById(undefined
)转换为findOne({ _id: null })
findById(undefined
findOne({ _id: null })
。
您可以看到问题是findById()
了_id
而不是json { _id : id }
。 所以改变:
campgrounds.findById({ _id: req.params.id })...
至
campgrounds.findById({ req.params.id })...
其余代码看起来不错(除了Daniel指出的consol.log()
之外)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.