Expressjs使用对象标题作为动态URL

时间:2014-10-03 20:13:11

标签: javascript node.js mongodb express

我试图找出如何通过标题而不是ID来路由我的GET单个对象路由参数。我知道body-parser允许请求,但无法弄清楚如何修改我当前的路由设置以允许这种情况发生。

我的想法是将所有blogpost_id更改为blogpost_title,但我遇到了这个错误。

{
  "message":"Cast to ObjectId failed for value \"Data Cost Upload\" at path \"_id\"",
  "name":"CastError",
  "type":"ObjectId",
  "value":"Data Cost Upload",
  "path":"_id"
}

routes.js:

//Route for individual blogs
    router.route('/blog/:blogpost_id')


    // START GET method blog by ID  
    .get(function(req, res) {



        Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {
            if (err)
                res.send(err);


            //res.json(blogpost);
            res.render('pages/blogpost', {
                blogpost: blogpost
            });
        });
    }) // END GET method blog by ID

    // START PUT method
    .put(function(req, res) {

        Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {

            if (err)
                res.send(err);


            blogpost.title = req.body.title; // update the blog title
            blogpost.author = req.body.author; // update the author name
            blogpost.tagline = req.body.tagline; // update the tagline
            blogpost.content = req.body.content; // update the blog content
            blogpost.category = req.body.category; // update the category 
            blogpost.tags = req.body.tags; //update the tags


            blogpost.save(function(err) {
                if (err)
                    res.send(err);


                res.json({ message: 'Blog updated.' });
            });

        });

    }) // END PUT method

    // START DELETE method
    .delete(function(req, res) {

        Blogpost.remove({
            _id: req.params.blogpost_id

        }, function(err, bear) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });

我如何链接到每个单独的对象:

<div class="blog-content">
                <% blogpost.forEach(function(blogpost) { %>
                    <tr>
                        <td><h2><a href="#" class="blog-title"><%= blogpost.title %></a></h2></td>
                        <td><h3><%= blogpost.date %></h3></td>
                        <td><h3 class="blog-category"><%= blogpost.category %></h3></td>
                        <td><h3 class="blog-tagline"><i><%= blogpost.tagline %></i></h3></td>
                        <td><p><%=: blogpost.content | truncate:800 | append:'...' %></p></td>
                        <td><a href="/blog/<%= blogpost.title %>" class="blog-read-more">Read More</a></td>
                    </tr>
                    <% }); %>
            </div>

点击“阅读更多”的结果网址:http://localhost:8080/blog/Data%20Cost%20Upload

1 个答案:

答案 0 :(得分:0)

当你得到http://localhost:8080/blog/Data%20Cost%20Upload

时 使用route.get调用的

req.params.blogpost_id = "Data Cost Upload"处理程序。

Blogs.findById预计第一个参数为mongoose.Types.ObjectId,但req.params.blogpost_idstring

如果您想按标题获取博客帖子,请使用

function getSearchCriteria(params) {
      return {
          title: params.blogpost_title
      };
}

function getBlogpostUpdate(body) {
      return {
           title: body.title,
           author: body.author,
           tagline: body.tagline,
           content: body.content,
           category: body.category,
           tags: body.tags
      };
}

var blogpostsRoute = router.route('/blog/:blogpost_title');

// to manipulate your route params, use router.param
router.param('blogpost_title', function (req, res, next, blogpost_title) {
    req.params.blogpost_title = blogpost_title.toLowerCase();
    next();
});

blogpostsRoute 
    .get(function (req, res) {
         var searchCriteria = getSearchCriteria(req.params);
         Blogpost.findOne(searchCriteria, function (err, blogpost) {
             if (err)
                 res.send(err);
             res.render('pages/blogpost', {
                 blogpost: blogpost
             })
         })
     })
     .put(function (req, res) {
         var searchCriteria = getSearchCriteria(req.params);
         var updated = getBlogpostUpdate(req.body)
         Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
             if (err)
                 res.send(err);


             res.json({ message: 'Blog updated.' });
         });
     })
     .delete(function (req, res) {
         var searchCriteria = getSearchCriteria(req.params);
         Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
             if (err)
                res.send(err);

             res.json({ message: 'Successfully deleted' });
         });
     });