Express.js从MongoDB ID创建URL

时间:2014-07-31 06:25:28

标签: javascript node.js mongodb express pug

我是node.js和express.js的新手。我试图创建一个像这样工作的待办事项应用程序: 我有一个包含个人待办事项列表的Todos mongodb。这些列表具有分类为未完成或已完成的任务。例如:

{
Todos: {
    Todo: {
        "_id" : ObjectId("5202b481d2184d390cbf6eca"),
        finished: ['walk dog', 'do dishes'],
        unfinished: ['clean room']
    }
    Todo: {
        "_id" : ObjectId("5202b49ad2184d390cbf6ecb"),
        finished: ['clean car', 'make dinner'],
        unfinished: ['write this damn web app ']
    }
}
}

我想为每个待办事项列表创建新页面,以便列表位于以下位置:http://website.com/5202b49ad2184d390cbf6ecb

所以我的问题是,如何动态创建URL?

谢谢!


编辑:

我将此代码添加到routes / index.js:

/* POST to New todo list service */
router.post('/:id', function(req, res) {
    var db = req.db;
    var tasks = db.get('taskscollection');
    tasks.insert({
        "id":req.params.id,
        "finished":[""],
        "unfinished":[""]
        }, function(err, doc) {
            if (err) {
                res.send("there was a problem with adding a new tasklist");
                }
            else {
                res.location("/:id");
                res.redirect("/:id");
                }
            });
    });

这个代码到index.jade:

   form#formNewTask(name='newtask', method='post', action='/:id')
     button#btnSubmit(type="submit") New Task List

但是当我点击按钮时,我被重定向到localhost:3000 /:id并且我找不到404。我在这里缺少什么?

另外,如何为新页面创建玉石模板?


编辑2:

我将index.js改为:

/* POST to New todo list service */
router.post('/tasks/:_id', function(req, res) {
    var db = req.db;
    var tasks = db.get('taskscollection');
    tasks.insert({                                        
        "finished":[""],
        "unfinished":[""]
        }, function(err, doc) {
            if (err) {
                res.send("there was a problem with adding a new task\
list");
                }
            else {
                res.location("/tasks/"+req.params.id);
                res.redirect("/tasks/"+req.params.id);
                }
            });
    });

我的index.jade现在有了这个:

   form#formNewTask(name='newtask', method='post', action='/tasks/'+_id)
     button#btnSubmit(type="submit") New Task List

现在当我点击新任务时,它会将我带到localhost:3000 / tasks / undefined。这是否表明它没有在数据库中创建新条目?我认为我的前端玉文件错了,但我不确定。

1 个答案:

答案 0 :(得分:5)

app.get('/task/:id',
      function(req,res){
         //access the id by req.params.id
         //and use it to obtain data from mongodb

      });

检查req.params

在发布数据时,尚未创建对象。因此没有_id。我的建议是在将新对象发布到databasa时不使用参数只需使用'/ posttask /'之类的内容

app.post('/postnewtask/',...

并且您没有为'/ task /:id'编写get调用。您只是在写post电话。 你的获取应该是

app.get('/task/:id'...
//use req.params.id and get data from database and render