【发布时间】:2015-04-28 18:04:01
【问题描述】:
尝试在 Express JS 中创建我的第一个简单 CRUD,但我似乎找不到这个烦人的错误。
当我尝试更新一个字段时,该字段的 JSON 会输出到视图,而不是新数据。
【问题讨论】:
标签: json mongodb express controller
尝试在 Express JS 中创建我的第一个简单 CRUD,但我似乎找不到这个烦人的错误。
当我尝试更新一个字段时,该字段的 JSON 会输出到视图,而不是新数据。
【问题讨论】:
标签: json mongodb express controller
update 方法用于查找和更新文档,而不返回已更新的文档。基本上,您所做的是查找文档而不更新它们,因为update 函数的第一个参数是搜索条件。在更新其属性后,您需要使用 save 函数来更新现有文档。
您的代码如下,已修改(未测试):
//PUT to update a blob by ID
.put(function(req, res) {
//find the document by ID
mongoose.model('Email').findById(req.id, function (err, email) {
//add some logic to handle err
if (email) {
// Get our REST or form values. These rely on the "name" attributes
email.email = req.body.email;
email.password = req.body.password;
email.servico = req.body.servico;
//save the updated document
email.save(function (err) {
if (err) {
res.send("There was a problem updating the information to the database: " + err);
}
else {
//HTML responds by going back to the page or you can be fancy and create a new view that shows a success page.
res.format({
html: function(){
res.redirect("/emails");
},
//JSON responds showing the updated values
json: function(){
res.json(email);
}
});
}
});
}
});
})
【讨论】: