简体   繁体   中英

how do i redirect in express with a given ID?

This code makes my app pick a random document from my mongoDB

router.get("/random", (req, res) => {
  try {
    postModel.countDocuments().exec(function(err, count) {
      var random = Math.floor(Math.random() * count);
      postModel
        .findOne()
        .skip(random)
        .exec(function(err, randomPost) {
          console.log(randomPost);
          res.render("play", { randomPost });
        });
    });
  } catch (err) {
    res.json({ msg: err });
  }
});

I have an ejs template which is named play.ejs, and it renders the file succesfully with the random chosen document.

But I want it to have a URL like /play/"idOfRandomChosenDocument" instead of /random everytime. How do I do this? Do I need to create router.get("/play/:postid") and if so, how do I pass in the id of the random document and it successfully loading with the right document objects?

Your code should be like this.

   router.get("/play/:postid", (req, res) => {
  try {
    postModel.countDocuments({_id:req.params.postid}).exec(function(err, count) {
      var random = Math.floor(Math.random() * count);
      postModel
        .findOne()
        .skip(random)
        .exec(function(err, randomPost) {
          console.log(randomPost);
          res.render("play", { randomPost });
        });
    });
  } catch (err) {
    res.json({ msg: err });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM