Reputation: 1072
I'm new to node.js and express.js. I'm trying to create a todo app that works like this: I have a mongodb of Todos containing individual todo lists. These lists have tasks classified as unfinished or finished. For example:
{
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 ']
}
}
}
I want to create new pages for each to do list, so that the lists are located as follows: http://website.com/5202b49ad2184d390cbf6ecb
So my question is, how can I create URLs on the fly like that?
Thanks!
I added this code to 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");
}
});
});
and this code to index.jade:
form#formNewTask(name='newtask', method='post', action='/:id')
button#btnSubmit(type="submit") New Task List
But when I click the button, I get redirected to localhost:3000/:id and I get a 404 not found. What am I missing here?
Also how do I create a jade template for the new page?
I changed my index.js to look like this:
/* 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);
}
});
});
And my index.jade now has this:
form#formNewTask(name='newtask', method='post', action='/tasks/'+_id)
button#btnSubmit(type="submit") New Task List
Now when I click new task, it takes me to localhost:3000/tasks/undefined. Does this suggest that it's not creating a new entry in the DB? I think my front end jade file is wrong but I'm not sure.
Upvotes: 2
Views: 2221
Reputation: 3744
app.get('/task/:id',
function(req,res){
//access the id by req.params.id
//and use it to obtain data from mongodb
});
Check req.params
As you are posting the data, the object is not yet created. Thus there is no _id. My advice is to not use a parameter when posting new objects into databasa just use '/posttask/' something like
app.post('/postnewtask/',...
And you are not writing a get
call for '/task/:id'. You are only writing a post
call.
Your get shall should be
app.get('/task/:id'...
//use req.params.id and get data from database and render
Upvotes: 5