10

I'm setting up a little API, I do some data validation on the client side of my application and whilst I do that I'm structuring my data to match my mongoose schema.

I'm attempting to do this...

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, this is currently removing all the model parameters of car provided by mongoose, so the save method e.t.c are no longer functional.

I have attempted car.data = req.body but this requires all of my mongoose schemas to be wrapped into a data object which isn't so elegant.

I was wondering if there was any way to avoid preparing the car object to be saved without the long-hand of;

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

e.t.c.

I'm essentially wanting to do the equivalent of car.push(req.body); but again, the .push() method is not available to mongoose models.

zupcfevf
  • 103
  • 1
  • 1
  • 5

1 Answers1

15

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

var car = new Car(req.body);

Here's also a reference: Passing model parameters into a mongoose model

Community
  • 1
  • 1
Carlo Gonzales
  • 365
  • 2
  • 9
  • My question is: is this secure? Like... couldn't someone include a function `save` inside `req.body` and mess with the entire thing? – Fusseldieb Jun 12 '19 at 17:00