kinhs
kinhs

Reputation: 195

How do I get this post params id in this route path?

Is this possible? I am still learning in this journey. So, I am trying to figure out if this is possible to get. I am building a blog using node.js, mongodb, mongoose and expressjs. I have a route path like this:

 const router = require("express").Router()
 const Comment = require("../models/Comment")
 const Post = require("../models/Post");
  router.delete("/posts/:id/comment/:id", async (req, res) =>{
    
 
 }

So, basically, we want to create a comment in this path and under this posts's id.

So, can I get the post's id? I mean, can I get the id of the post on which this comment is made? I can get the params id of the comment but I don't know how to get the posts/id. I did something like this:

const post = Post.findById(req.params.id) this didnt get the post.

const comment = Comment.findbyId(req.params.id) this found the comment id. 

If this is possible, kindly tell me how to. If it is not possible, kindly provide me with an alternative way to do it. Thanks.

Upvotes: 1

Views: 1906

Answers (2)

Simas Butavičius
Simas Butavičius

Reputation: 296

The problem is, you use same name for both route parameters (:id), so express router can't distinguish if you want post :id or comment :id. Rename /posts/:id/comment/:id to something like /posts/:postID/comment/:commentID and then both parameters will be available in your code as req.params.postID and req.params.commentID.

Upvotes: 4

AhmCho
AhmCho

Reputation: 390

You are using id both for post id and comment id. req.params will only get that latter id, which probably isn't something you want. Instead, you could differentiate these id-s semantically and use more clear names for them. For example:

router.delete("/posts/:post_id/comment/:comment_id", async (req, res) =>{
   //your code
}

Upvotes: 2

Related Questions