Node.js mongoose更新文档

C. *_*rto 1 mongoose node.js

我对在节点中更新某些文档的最佳实践感到困惑,例如,我不知道是否应该通过req.body更新多个字段(这会让我更容易):

//course is the document and Course is the model
util.updateDocument(course, Course, req.body);
Run Code Online (Sandbox Code Playgroud)

或者如果我应该创建多个post方法,每个方法都有一个文档字段来更新并从客户端连续请求它们:

app.put('/updatecourse/:field1',function(req, res){});
app.put('/updatecourse/:field2',function(req, res){});
app.put('/updatecourse/:field3',function(req, res){});
Run Code Online (Sandbox Code Playgroud)

目前我正在使用通过req.body接收文档的任何字段并更新它的函数,但是从我听到的这不是一个好的做法,加上方法不是异步的.有人可以向我解释这种情况的最佳做法是什么?

小智 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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

在这里,您将期望使用id(或Mongoose _id)参数触发路由.首先,我们要检查模型是否存在该ID,如果不存在,我们将返回带有404状态代码的NotFound响应.如果模型存在,则使用新属性更新它.

在Mongoose中,您也可以使用该findByIdAndUpdate方法更新模型.这是对数据库的原子操作,不应用模型验证或默认值.此外,不会触发前/后挂钩.

点击此处查看文档

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);
  });
});
Run Code Online (Sandbox Code Playgroud)