node.js - 如何从一个集合中传递一个 id 并使用它来使用 mongoose 和 nodejs 设置另一个模型
问题描述
这篇文章AddComment 在点击添加评论按钮时触发
exports.postAddComment=(req,res,next)=>{
let id=req.body.id;
const text=req.body.comment;
Post.findById(id)
.then(res=>{
console.log(res)
const comment=new Comment({
comment:text,
postId:new mongoose.Types.ObjectId(res._id),
userId:req.user
})
return comment.save()
}).then(result=>{
res.redirect('/add-comment/postId')
})
}
实际上我想启用对帖子的评论,为此我有一个不同的评论模型,我想在这个评论模型中设置帖子(另一个模型)引用我尝试了一切,但总是收到 CastError 的错误
解决方案
如果您在模型中将 postId 声明为 objectId,则可以这样使用:
const comment=new Comment({
comment: text,
postId: res._id,
userId: req.user
})
类型res._id是objectId :)
并确保req.body也是objectId。
comment.save() 是异步函数。所以你必须这样做:
comment.save().then(c => {
return c;
})
推荐阅读
- python - 在本地运行 python 脚本与在 docker 中运行的区别
- ios - 无法在 python3 中构建 pycrypto 配方 - 工具链
- jdbc - 如何使用 JDBC 获得确切的 Sybase ASE 版本?
- python - 如何从 JSON 多维追加动态下拉列表
- c - 为什么 x 有垃圾价值?
- office-js - 使用 Outlook 插件/office.js 时有没有办法确定约会的形式类型
- flutter - Flutter - 如何在左上角创建带有标签的卡片?
- scala - 有没有办法将匹配与布尔值一起使用
- c# - 如何针对上下文执行 RawSql
- eclipse - 在同步 pespetcive 中找不到本地文件夹