【发布时间】:2018-03-11 04:28:02
【问题描述】:
在主页上,有一个带有profile/5aa3cfb783622a145a86d616的超链接指向用户的个人资料页面,其中5aa3cfb783622a145a86d616是用户的对象ID(在MongoDB中显示为"_id" : ObjectId("5aa3cfb783622a145a86d616"))。
当我点击链接时,页面完全加载没有任何问题。但是,终端仍然显示Cast to ObjectId failed for value "..." at path "_id" for model "User",并且浏览器的图标仍然显示正在加载,即使页面已完全加载。
我尝试寻找答案,但没有一个是针对我的问题的。
编辑
在玩了代码之后,我发现问题似乎在于多个“填充”方法,我之前在简化问题时忽略了这些方法,因为我认为它没有问题。我现在在下面包含完整的代码。
在 User 文档中,有一个 Post 数组,其中包含 Post 的 ID。每个帖子文档都有作者、喜欢和评论。在 Comment 数组中,每个评论文档都有作者的 ID。所有这些都必须填充。
NodeJS/猫鼬:
router.get("/:id", function(req, res){
User.findById(req.params.id).populate({
path: 'posts',
populate: [{
path: 'author',
},
{
path: 'likes',
},
{
path: 'comments',
populate: [{
path: 'author'
}]
}]
})
.exec(function(err, user){
console.log(user);
res.render("profile", {user: user});
});
});
用户架构
var UserSchema = new mongoose.Schema({
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Post"
}
]
});
发布架构
var postSchema = mongoose.Schema({
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
likes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
],
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
评论架构
var commentSchema = mongoose.Schema({
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
});
当我console.log(user)时,终端返回以下内容。我不太清楚为什么它显示author[object] 而不是它的实际ID,也许这是问题所在?
{ posts:
[ { likes: [],
comments: [],
_id: 5aa3d0d806711d1483ae7e3e,
__v: 0,
author: [Object] },
{ likes: [],
comments: [],
_id: 5aa3cfc483622a145a86d618,
__v: 0,
author: [Object] },
{ likes: [],
comments: [],
_id: 5aa3cfbe83622a145a86d617,
__v: 0,
author: [Object] } ],
__v: 3}
编辑 2
很奇怪,我的其他具有相同结构的路线(friendPosts 除外)可以正常工作。
router.get("/home", function(req, res){
User
.findById(req.user._id)
.populate({
path: 'friendPosts',
populate: [{
path: 'author',
},
{
path: 'likes',
},
{
path: 'comments',
populate: [{
path: 'author'
}]
}]
})
.exec(function(err, currentUser){
res.render("main/home", {user: currentUser});
});
});
【问题讨论】:
-
控制台你的 req.params.id 看看它有什么......
-
尝试将
id从string转换为ObjectId,例如:User.findById(ObjectId.fromString( req.params.id), ... -
@AshishChoudhary 它显示
5aa3cfb783622a145a86d616。 -
@Taki 代码编辑器说
ObjectId is not defined; please fix or add /* global ObjectId */? -
@steven 试试这个
User.findOne({_id: req.params.id }, function (err, user) { ... })