首页 > 解决方案 > 如何从一个集合中传递一个 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 的错误

标签: node.jsexpressmongoose

解决方案


如果您在模型中将 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;
   })

推荐阅读