我想使用节点js和MongoDB数据库更新表单日期。 我用main.js创建服务器文件并处理请求方法如下
app.get('/edit/:id', (req, res) => {
var id = req.params.id;
var o_id = new ObjectId(id);
db.collection('blogs').find({_id:o_id}).toArray((err, result) => {
if (err) return console.log(err)
console.log(result);
res.render('edit.ejs',{blogs: result});
});
console.log(req.params.id);
});
app.post('/edit',(req, res) => {
db.collection('blogs').update ({ _id: req.body._id }, {$set: {
title: req.body.title,
description: req.body.description
}
}, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Post Updated successfully");
res.render('blog.ejs');
}
});
修改视图
<form action="/edit" method="POST">
<div class="form-group">
<label for="title">Title:</label>
<input type="text" id="title" class="form-control" name="title" value="<%= blogs[0].title %>">
</div>
<div class="form-group">
<label for="description">Description:</label>
<textarea name="description" id="description" class="form-control"><%= blogs[0].description %></textarea>
</div>
<input type="hidden" name="_id" value="<%= blogs[0]._id %>">
<button type="submit" class="btn btn-info">Submit</button>
</form>
表单提交后,显示&#34;发布更新成功&#34;但数据没有变化。
答案 0 :(得分:0)
app.get('/edit/:id', (req, res) => {
var id = req.params.id;
var o_id = new ObjectId(id);
db.collection('blogs').find({_id:o_id}).toArray((err, result) => {
if (err) return console.log(err)
console.log(result);
res.render('edit.ejs',{blogs: result});
});
console.log(req.params.id);
});
app.post('/edit',(req, res) => {
db.collection('blogs').update ({ _id: ObjectId(req.body._id) }, {$set: {
title: req.body.title,
description: req.body.description
}
}, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Post Updated successfully");
res.render('blog.ejs');
}
});
在ObjectId中,您已经在代码中需要一些位置
var objectID = require('mongodb').ObjectID;