F
F
filisonov2021-04-14 18:49:14
Express.js
filisonov, 2021-04-14 18:49:14

How to properly set up a route in a NodeJS+express+mongoose app?

Route set up:

router.route('/:category/:id')
    .get(defaultController.singlePost);


Set up controller:
singlePost:async (req, res) => {
        const id = req.params.id;
        const categories = await Category.find().lean();
        const categoryTitleId = Category.findOne({category:req.params.category});
        console.log(req.params.category);
        console.log(categoryTitleId);
        /***/
        Post.findById(id).lean()
            .then(post => {
                res.status(200);
                res.setHeader('Content-Type', 'text/html; charset=utf-8');
                res.render('default/singlePost', {post: post, categories: categories});
            })
            .catch(function(err) {
                //res.status(404).json({message: 'No post found'});
                res.status(404);
                res.setHeader('Content-Type', 'text/html; charset=utf-8');
                res.render('404.handlebars', { url: req.url });
                return;
                //return res.json(err);
            });
        /***/

   }


The URL itself in the html document is formed using handlebars:
<a href="/{{category}}/{{_id}}" class="btn btn-primary">Read More &rarr;</a>


Everything works fine, but how can I now deduce the URL that fetches by ID /606f4f50ac91981f9ce9bd38/606f5f18122c0c1344014f5e , the URL is /catName/postName

PS. In the model (Model) of the post, the attached category is saved as an ID, I can pull it out, but how can I find the Category Name by this ID, and pass it to the URL.
I haven't been able to find a solution for 2 days now.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question