0
我正在使用Node,Express和MongoDB創建博客。我正在使用Mongoose連接到MongoDB。Node.js&Express:需要根據POST值重定向到特定頁面(使用MongoDB)
我有一個創建新的帖子窗體,在MongoDB中創建和保存新帖子就好了。
創建帖子時,您可以將帖子標記爲發佈或者不選中該選項。當您保存帖子時,我希望您可以:
A)如果發佈帖子被重定向到主頁,或者 B)被重定向到帖子的編輯/更新頁面(如果該帖子未被標記爲出版。
下面是在我試圖用它來完成視圖上面代碼中的:
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");
}
});
}
這是發送POST數據對應的視圖:
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
任何幫助不勝感激!謝謝!
嗯。我認爲POST變量是好的。當我登錄'request.body.post'到控制檯它吐出: {標題: '測試', 別名: '', 小標題: '', 預覽: '', 體: '', 發表:'on'} 我想我必須弄清楚如何從剛剛保存的Post對象中獲取對象ID,以傳遞給URL(然後將匹配編輯帖子視圖)。另外,我只是將第一部分改爲:'if(req.body.post.published){ return res.redirect(「/」);並且固定那部分。 – 2013-03-08 17:34:47
'Plain'Express不處理我相信命名的屬性類型,因此需要額外的代碼來處理它們(但如果它沒有它,那麼它很適合:)。您是否注意到了重定向中的'post._id'?貓鼬應該在保存時填充它。 – robertklep 2013-03-08 17:54:08
謝謝,就是這樣。代碼最終看起來如何:'addPost:function(req,res){var newPost; newPost = new Post(req.body.post); return newPost.save(function(){ if(req.body.post.published){ return res.redirect(「/」); } else { return res.redirect(「/ office/post /」 + newPost._id +「/ edit」); } }); '欣賞幫助! – 2013-03-10 22:34:20