I am creating a blog with Node, Express and MongoDB. I'm using Mongoose to connect to MongoDB.
I have a create new post form that creates and saves new posts in MongoDB just fine.
When creating a post you can mark the post as published or leave that option unchecked. When you save the post I want you to either:
A) Be redirected to the home page if the post was published, or B) be redirected to the post's edit/update page if the post was not marked to be published.
Here's the code in the view that I'm trying to use to accomplish the above:
addPost: function(req, res) {
return new Post(req.body.post).save(function() {
if (req.body.published === true) {
return res.redirect("/");
} else {
return res.redirect("/office/post/" + [NEED OBJECT ID HERE] + "/edit");
}
});
}
This is the corresponding view that sends the POST data:
form.web-form(method="post", action="/post/new")
fieldset.fieldset
label.form-label(for="title") Title
input.text-input(id="title", type="text", name="post[title]", placeholder="Post title")
input.text-input(id="alias", type="hidden", name="post[alias]")
label.form-label(for="subhead") Subhead
input.text-input(id="subhead", type="text", name="post[subhead]", placeholder="Post subhead")
label.form-label(for="preview") Preview
textarea.text-area(id="preview", name="post[preview]", rows="4", placeholder="Preview")
label.form-label(for="post-body") Body
textarea.text-area(id="post-body", name="post[body]", rows="5", placeholder="Main content")
input.check-box(onclick="changeButton()", id="published", type="checkbox", name="post[published]")
label.inline-label(for="published") Publish
input.btn-submit(id="submit-post", type="submit", value="Save!")
a.btn-cancel(href="/") Cancel
Any help is greatly appreciated! Thanks!
Like this?
addPost: function(req, res) {
// strip 'post[' and ']' from submitted parameters
var params = {};
for (var k in req.body)
{
params[k.substring(5, k.length - 1)] = req.body[k];
};
var post = new Post(params);
return post.save(function() {
if (params.published === true) {
return res.redirect("/");
} else {
return res.redirect("/office/post/" + post._id + "/edit");
}
});
}