GY22
GY22

Reputation: 785

How to create routes with unique ids in NodeJS

So i am working on a project with node, express, mongoose en mongodb. I am able to create/save a topic to the db. but when the topic is saved/created i want to redirect the user to the topic details page of that created topic (so basically every created topic has its own unique url based of the id, like so -> localhost:3000/topicdetail/id)

The problem with me is that upon redirecting i get an error saying: Error: Failed to lookup view "error" in views directory "/Users/Grace/Desktop/QA/views"

So my main question is am i redirect it correctly with its own unique id or am i doing something else wrong. Any help is welcome.

my code is the following:

var mongoose = require('mongoose');
var Topic = require('../models/topic');
var db = require('../config/database');
var express = require('express');
var router = express.Router();

// render the start/create a new topic view
router.get('/', function(req, res) {
  res.render('newtopic');
});

// save topic to db
router.post('/',function(req, res, next){
console.log('The post was submitted'); 

var topic = new Topic
({
    "topicTitle":       req.body.topicTitle,
    "topicDescription": req.body.topicDescription,
    "fbId":             req.body.userIdFB,
    "twId":             req.body.userIdTW
})

topic.save(function (err, topic)
{
    if(err){
        return next(err)
        console.log('Failed to save the topic to the database');
    }
    else
    {
        console.log('Saved the topic succesfully to the database');
        // each topic has its own unique url 
        res.redirect('/topicdetail/{id}');
    }
})

});

module.exports = router;

Upvotes: 1

Views: 2057

Answers (1)

r0-
r0-

Reputation: 2498

Calling res.redirect('/topicdetail/{id}'); won't insert any ID. Express won't reformat the string. It takes your defined redirect, in this case /topicdetail/{id}and performs it. Just like you would insert it into your browser.

To redirect your detail view you could do something like: res.redirect('/topicdetail/' + topic._id); and replace topic.id with something like your document ID or another identifier.

Just a reminder: Your detail route needs a param in the route definition. Example: app.get('/verification/:token', users);. The :token is your param. More about in the routing guide.

Upvotes: 1

Related Questions