How to pass a id from one collection and use it to set another model using mongoose with nodejs

Viewed 267

this postAddComment fire on clicking on add comment button

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')
  })
}

Actually i want to enable comments on posts and for that I have aa different model for the comments and I want to set Posts(another model) reference in this comments model I tried everything but always getting an error of CastError

1 Answers

if you declare postId as objectId in your model, you can use like this :

    const comment=new Comment({
        comment: text,
        postId: res._id,
        userId: req.user
    })

typeof res._id is objectId :)

and make sure that req.body is objectId too.

comment.save() is the async function. so you must do :

   comment.save().then(c => {
       return c;
   })
Related