我对更新节点中某些文档的最佳做法感到困惑,例如,我不知道是否应该通过req.body更新多个字段(这会让我更容易):
//course is the document and Course is the model
util.updateDocument(course, Course, req.body);
或者我应该创建多个post方法,每个方法都有一个文档字段来更新并从客户端连续请求它们:
app.put('/updatecourse/:field1',function(req, res){});
app.put('/updatecourse/:field2',function(req, res){});
app.put('/updatecourse/:field3',function(req, res){});
目前我正在使用通过req.body接收文档的任何字段并更新它的函数,但是从我听到的这不是一个好习惯,加上方法不是异步的。有人可以向我解释这种情况的最佳做法是什么?
答案 0 :(得分:6)
我总是希望为每个模型都有一个REST API。所以我能给你的解决方案就是UPDATE
操作的例子:
app.put('courses/:id', function(req, res, next) {
var id = req.params.id,
body = req.body;
Courses.findById(id, function(error, course) {
// Handle the error using the Express error middleware
if(error) return next(error);
// Render not found error
if(!course) {
return res.status(404).json({
message: 'Course with id ' + id + ' can not be found.'
});
}
// Update the course model
course.update(body, function(error, course) {
if(error) return next(error);
res.json(course);
});
});
});
在这里,您可以期望使用id
(或Mongoose _id
)参数触发路由。首先,我们想检查模型是否存在该ID,如果不存在,我们将返回带有404
状态代码的NotFound响应。如果模型存在,则使用新属性更新它。
在Mongoose中,您也可以使用findByIdAndUpdate
方法更新模型。这是对数据库的原子操作,不应用模型验证或默认值。此外,前/后挂钩也不会被触发。
Check here for the documentation
app.put('courses/:id', function(req, res, next) {
var id = req.params.id,
body = req.body;
Courses.findByIdAndUpdate(id, body, function(error, courses) {
// Handle the error using the Express error middleware
if(error) return next(error);
// Render not found error
if(!course) {
return res.status(404).json({
message: 'Course with id ' + id + ' can not be found.'
});
}
res.json(course);
});
});