'Express APP how to redirect user to /:id path from server side

I'm learning Node.js and I'm finding some troubles with redirecting the user to an :id path. I would like to print there his username. So to make an overview it is a landing page with a form where I ask for an Alias and an email. When user clicks submit I'd like to move him to /:id path to print its' username. My code is the following:

var express  = require("express"),
    app      = express(),
    request  = require("request"),
    mongoose = require("mongoose"),
    bodyParser = require("body-parser");

app.set("view engine", "ejs")
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));

mongoose.connect("mongodb://localhost/Scape_Room", {useNewUrlParser: true, useUnifiedTopology: true});
var userSchema = new mongoose.Schema({
    email: String,
    alias: String,
});

var user = mongoose.model ("user",userSchema);

app.get("/", function(req, res){
    res.render("index")
})

app.post("/newuser", function(req,res){
    var name = req.body.name;
    var email = req.body.email;
    var newUser = {name:name, email:email}
    user.create(newUser, function(err,newlyUser){
        if(err){
           console.log(err)
           } else {
               res.redirect("/start/:id")
           }
    })
})

app.get("/start/:id", function(req,res){
    user.findById(req.params.id, function(err, foundUser){
        if(err){
            console.log(err)
        } else{
            res.render("startPoint", {user:foundUser})
        }
    })
})

app.listen(3000, function(err){
        console.log("Server listening")
})

error is the following: { CastError: Cast to ObjectId failed for value ":id" at path "_id" for model "user"

I've tried: - to change the path to :_id - added start/ into the route



Solution 1:[1]

Use something like below

app.post("/newuser", function(req,res){
    var name = req.body.name;
    var email = req.body.email;
    var newUser = {name:name, email:email}
    user.create(newUser, function(err,newlyUser){
        if(err){
           console.log(err)
           } else {
               res.redirect(`/start/${newlyUser._id}`)
           }
    })
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shubh