Mongoose saves all parameters from the request body

I create a small API, I do some data validation on the client side of my application, and while I do this, I structure my data according to my mongoose scheme.

I'm trying to do it ...

router.route('/car') .post(function(req, res) { var car = new Car(); car = req.body; // line under scrutiny car.save(function(err) { if(err) { console.log(err); res.status(400); res.send(err); } else { res.status(200); res.json({ message: req.body.name + ' successfully registered!' }); } }); }); 

but, of course, all car model parameters provided by mongoose are currently being deleted, so the save etc method no longer works.

I tried car.data = req.body , but this requires all my mongoose schemes to be wrapped in a data object, which is not so elegant.

I was wondering if there is a way to avoid preparing a car object that would be saved without long arms,

 car.name = req.body.name; car.seats = req.body.seats; car.engine_size = req.body.engine_size; 

etc

I essentially wish to make the equivalent of car.push(req.body); , but again .push() not available for mongoose models.

+8
javascript mongodb mongoose express
source share
1 answer

You can pass req.body to your Car , like this

 var car = new Car(req.body); 

Here is also a link: Passing model parameters to the mongoose model

+11
source share

All Articles