zupcfevf
zupcfevf

Reputation: 103

Mongoose save all parameters from request body

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.

Upvotes: 10

Views: 15137

Answers (1)

Carlo Gonzales
Carlo Gonzales

Reputation: 365

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

Upvotes: 15

Related Questions