Reputation: 3707
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;
Upvotes: 2
Views: 7549
Reputation: 2108
You can use Document.set().
car.set(req.body)
try {
await car.save()
}catch(err){
console.error(e)
}
Upvotes: 3
Reputation: 1885
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.
Upvotes: 0
Reputation: 487
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);
});
});
Upvotes: 4