Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 920
zupcfevf Avatar asked Dec 05 '14 12:12

zupcfevf


People also ask

What is the use of save() function in mongoose?

Mongoose's save () function is one way to save the changes you made to a document to the database. There are several ways to update a document in Mongoose, but save () is the most fully featured. You should use save () to update a document unless you have a good reason not to. Working with save ()

How do I update a document in mongoose?

There are several ways to update a document in Mongoose, but save () is the most fully featured. You should use save () to update a document unless you have a good reason not to. Working with save () save () is a method on a Mongoose document.

What is mongoose pre and post function?

Mongoose middleware lets you tell Mongoose to execute a function every time save () is called. For example, calling pre ('save') tells Mongoose to execute a function before executing save (). Similarly, post ('save') tells Mongoose to execute a function after calling save ().

How to check mongoose version in command prompt?

After installing mongoose module, you can check your mongoose version in command prompt using the command. After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.


1 Answers

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

like image 200
Carlo Gonzales Avatar answered Oct 09 '22 14:10

Carlo Gonzales