1
votes

I'm confused about best practices to update certain documents in node, for example, I don't know if I should update multiple fields through req.body (which would make everything easier for me):

//course is the document and Course is the model
util.updateDocument(course, Course, req.body);

or if I should create several post methods each with one field of the document to update and request them in a row from the client:

app.put('/updatecourse/:field1',function(req, res){});
app.put('/updatecourse/:field2',function(req, res){});
app.put('/updatecourse/:field3',function(req, res){});

Currently I'm using the function that receives any field of the document through req.body and updates it, but from what I heard that is not a good practice, plus the methods are not asynchronous. Can someone explain to me what are the best practices for this situation?

1

1 Answers

6
votes

I always prefer to have a REST API for each of my models. So the solution I can give you is the example of the UPDATE operation:

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);
    });
  });
});

Here you will expect that the route is triggered with an id(or Mongoose _id) parameter. First we would like to check if the Model exists for that ID, if it does not, we would return a NotFound response with a 404 Status Code. If the model exists update it with new properties.

In Mongoose, you can update the model using the findByIdAndUpdate method as well. This is an atomic operation on the database, and no Model validation or default values are applied. Also the pre/post hooks would not be triggered.

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);
  });
});