javascript - Mongoose 对象在填充时返回未定义
问题描述
我正在努力解决一个小问题。我想做的是在评论中填充用户。
用户架构:
const userSchema = mongoose.Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true
}
});
评论架构:
const commentSchema = mongoose.Schema({
comment:{
type: String
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
});
我已经创建了用户和评论。当我试图找到两个对象时,一切都很好。
评论:
Comment.find({}).exec((err, comments) => {
console.log(comments);
});
输出:
[
{
_id: 5e62472d5f593f3c642ee1e5,
comment: 'something',
user: 5e624522366d8c4150278a64,
__v: 0
}
]
用户:
User.find({}).exec((err, users) => {
console.log(users);
});
输出:
[
{
_id: 5e624522366d8c4150278a64,
username: "SomeBodY",
password: "$2a$10$nm5BJ7zeI1tet3UEzcakf.8xoTgV/Yti5l1EKNg5inxiehevUlGRm"
}
]
问题是当我.populate('user')
用来建模时,它会像在控制台中Comment
一样返回注释。undefined
我尝试了不同的方法,甚至删除了数据库,但没有成功。
这是发生这种情况时的路线
// Route To Single Project
router.get('/:projectId', (req, res) => {
const requestedProjectId = req.params.projectId;
Project.findById({_id: requestedProjectId}).populate('image_file').exec((err, project) => {
Rating.find({projectId: requestedProjectId}, (err, ratings) => {
Rating.countDocuments({projectId: requestedProjectId}, (err, count) => {
Comment.find({projectId: requestedProjectId}).populate('user').exec((err, comments) => {
console.log(comments)
if(err) return next(err);
res.render('project', { ... });
});
});
});
});
});
解决方案
实际上,您的填充代码是正确的。
得到空评论的原因是因为这Comment.find({projectId: requestedProjectId})
似乎返回空。所以只需检查您的请求参数。
为了摆脱回调地狱,您可以像这样使用 async/await 重写您的路由。
router.get("/:projectId", async (req, res) => {
const requestedProjectId = req.params.projectId;
try {
const project = await Project.findById({ _id: requestedProjectId }).populate("image_file");
if (!project) {
return res.status(400).send("Project not found, check your projectId");
}
const comments = await Comment.find({ projectId: requestedProjectId }).populate("user");
console.log(comments);
const ratings = await Rating.find({ projectId: requestedProjectId });
const count = await Rating.countDocuments({ projectId: requestedProjectId });
res.render("project", {
project,
comments,
ratings,
count
});
} catch (err) {
console.log("Error: ", err);
res.status(500).send("Something went wrong");
}
});
推荐阅读
- typescript - 如何在类型脚本中创建不同的通用函数?
- python - 处理 '&' 在 url 参数 DJANGO
- sql - SQL 缺少关键字
- r - 如何根据其他两个变量的所有组合获得一个显示一个变量平均值的三向表?
- java - 尝试运行主类时将 SQL 转换为 MapReduce java.lang.NoSuchMethodException
- reactjs - 我应该为对象休息道具声明什么类型?
- visual-studio - Tfs 尝试合并错误的变更集
- abap - CL_SALV_TABLE 网格列的“F1”屏幕中缺少技术信息
- twitter - 以阿拉伯语购买特定时期和特定关键字的历史推文
- angular - angular-bootstrap-datetimepicker Angular 6 刷新视图的问题