DEV Community

Discussion on: Help me with the display of the url

Collapse
 
oliversd profile image
Olivers De Abreu

Maybe the error is here:

app.put("/blog/:title", function(req, res){
    Blog.findOneAndUpdate({title: req.params.title}, req.body.blog, function(err, updatedBlog){
        if(err){
            res.redirect("/blog");
        }
        else{
            res.redirect("/blog/"+req.params.title);
        }
    })
})

When you update the blog post, you are looking for the title, but if the title is different from the original, it won't find it and create a new entry on your database. I recommend that you use the id of the post to make sure that you are referring to the same entry.

Collapse
 
sanketnjain5 profile image
Sanket N Jain

If I use ID then I can't get the title on the URL. So is there any way to do it without the ID?
Can I store the updated title in a variable and use it in the URL?

Collapse
 
oliversd profile image
Olivers De Abreu

Yes you could do that and use it in the put. But it's not a great practice using a variable that change as a parameter in your endpoint.

Collapse
 
mozetsu profile image
Moz 🛸 • Edited

As I understood, you can update the document on the database right? I'm assuming that as a yes 😅 So the problem, for what I can tell, is that you reach the PUT endpoint and use the params to search the old title with "req.params.title".

When you finish updating the database the old title does not exist anymore, but you keep using the same URL that contains the old title to redirect the page.

Since your database cant find the old title you can not be redirected to the updated blog 😅, I suggest you change the "req.params.title" on your redirect call to "req.body.blog.title" since the blog object contains the new title. Hope I could help you 😄

Thread Thread
 
sanketnjain5 profile image
Sanket N Jain

OMG!! Thank you. I thought of this at first but forgot later. Now I'm getting the title in the URL!!😁😁