使用express和mongodb提供动态URL

时间:2012-12-06 16:10:42

标签: node.js mongodb url express

我正在构建一个具有类似reddit功能的网站。我希望用户提交的内容能够获得自己的页面。每个提交都分配了一个5个字符的ID,我想要在该页面的URL中。

我在路由器文件中有这个功能,它会呈现一个名为titles的页面:

exports.titles = function(req, res){
i = 0
read(function(post){
    url = post[i].URL;
    res.render('titles', {title: post[i].title, url: post[i].URL});
});

};

这个声明在app.js中提供:

app.get('/titles', home.titles); //home.js is the router file

标题页面包含文本post.title和URL post.URL的链接。当用户点击链接(例如domain.com/12345)时,他们应该被带到内容post.body的名为content的页面。

我如何a)将URL传回我的app.js文件以包含在app.get中,b)在此路由器文件中包含app.get函数,或c)以任何其他方式解决此问题? / p>

编辑:我确实有一个对象'titles'是一个mongodb集合,但它在一个不同的模块中。没理由我不能把它添加到路由器。

编辑:我尝试将其添加到app.js以查看它是否可行:

app.get('/:id', function(req, res){
  return titles.findOne({ id: req.params.id }, function (err, post) {
    if (err) throw(err); 

    return res.render('content', {title: post.title, content: post.body});
   });
});

编辑:我得到了它的工作。我所做的只是格式化标题,使其看起来像domain.com/titles/12345并更改app.get('/:id',更改为app.get('/ titles /:id,...

1 个答案:

答案 0 :(得分:11)

如果我做对了,我就会那样做。

短版

  1. 我会从网址
  2. 获取id
  3. 然后我会从数据库中提取与此id
  4. 相关联的数据
  5. 并使用此数据构建最终页面。
  6. 您无需为每个网址创建新路线。 URL可以包含一些变量(此处为id),Express可以解析URL以获取此变量。然后从这个id,您可以获得构建正确页面所需的数据。

    长版

    我假设有人在此网址中输入内容:http://domain.com/1234 我还假设您有一个变量titles,这是一个MongoDB集合。

    您可以拥有如下定义的路线:

    app.get('/:id', function(req, res) {
      // Then you can use the value of the id with req.params.id
      // So you use it to get the data from your database:
      return titles.findOne({ id: req.params.id }, function (err, post) {
        if (err) { throw(err); }
    
        return res.render('titles', {title: post.title, url: post.URL /*, other data you need... */});
      });
    });
    

    修改

    我根据最后的评论做了一些改变......