Hi there,
I am writing a little blog just for the purpose of learing some backend programming. So far I am able to create, read and delete posts from my mongoDB (mLab). But I am not able to update the displayed posts. I read every tutorial so far that I could find on how to update mongoDB but none seem to work with my setup.
My model:
var blogSchema = mongoose.Schema({
title: String,
post: String,
author: String,
createdAt: {
type: Date,
default: new Date()
}
});
var Blog = mongoose.model("Blog", blogSchema);
My current code for updating my posts look like this:
app.get("/editPost/:id", (req, res) => {
let id = ObjectID(req.params.id);
Blog.find(id, (err, post) => {
res.render("editPost", { post: post });
});
});
app.put("/editPost/:id", (req, res) => {
let id = req.params.id;
const updates = {
title: req.body.title,
author: req.body.author,
post: req.body.post
};
Blog.update(id, updates, (err, result) => {
if (err) {
res.send("error occurred");
} else {
res.send(updates);
}
})
.exec()
.then(result => {
res.redirect("/");
});
});
And the html for rendering:
<form action="/editPost/:id" method="GET">
<div class="container">
<div class="row">
<div class="col-sm">
<label style="display: block;" for="title">Title: </label>
<textarea style="padding-right: 60%" name="title"><%=post[0].title %></textarea>
</div>
</div>
<br />
<div class="row">
<div class="col-sm">
<label style="display: block;" for="author">Author: </label>
<textarea style="padding-right: 60%" name="author" ><%=post[0].author %> </textarea>
</div>
</div>
<br />
<div class="row">
<div class="col-sm">
<label style="display: block;" for="post">Post: </label>
<textarea style="padding-right: 60%; resize: both; overflow: auto " name="post"><%=post[0].post %></textarea>
</div>
</div>
<br />
<button type="submit">Edit Post</button>
</div>
</form>
Has anyone an idea how to display and update posts in my setup?