2

The question(Mongoose save all parameters from request body) shows how to create new mongoose document object with request body in a line of code.
Extending this question, I want to know how to set all fields of mongoose document object at once.

router.route('/car')
.put(function(req, res, next) {
  Car.findById(req.params.id, function (err, car) {
    if (err) {
      res.status(400).send(err);
    } else {
      if (!car)
        return next(new Error('Failed to load car: ' + req.params.id));

      car.name = req.body.name; // Code refactoring required
      car.seats = req.body.seats;
      car.engine_size = req.body.engine_size; 

      car.save(function(err) {
          if(err)
            res.status(400).send(err);
          else
            res.json(car);
      });
    }
  });
});

In creating document var car = new Car(req.body); is perfect way to fill fields from request body.
For updating exist mongoose document, is there better way than below lines:

car.name = req.body.name;
car.seats = req.body.seats;
car.engine_size = req.body.engine_size; 
Community
  • 1
  • 1
Hill
  • 3,391
  • 3
  • 24
  • 28

3 Answers3

4

You should use update instead of find.

router.route('/car')
.put(function(req, res, next) {
  Car.update({ _id: mongoose.Types.ObjectId(req.params.id) },req.body)
    .then(function (success) {
      res.json();
    })
    .catch(function (error) {
        res.status(404).send(err);
    });
});
Max Kroshka
  • 457
  • 2
  • 5
  • 1
    This is easier and also faster then find + save but it doesn't trigger validators, setters, middleware and defaults (http://mongoosejs.com/docs/api.html#update_update) – julian libor Jun 18 '18 at 12:11
2

You can use Document.set().

car.set(req.body)
try {
    await car.save()                  
}catch(err){ 
    console.error(e)
}
Tomáš
  • 2,078
  • 3
  • 22
  • 21
0

For updating exist mongoose document, Is there better way than below lines?

For the better utilization of network data and performance, You should keep in mind that, update() method updates values in the existing document while the save() method replaces the existing document with the document passed in save() method.

So if your model is large and you want to update only few number of fields then update is better option.

Hope this helps.

Sandeep Sharma
  • 1,855
  • 3
  • 19
  • 34
  • To the best of my knowledge, save() diffs first between the current state of the document and the db state, and only sends the diff. save() does not replace the object entirely. Considering the document exists on the db, the difference here is that save() requires you to first request the document from the db, while update() doesn't. In other words - save() is a client side operation while update() is server side. – Vaiden Sep 18 '17 at 16:13