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.
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 ()
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.
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 ().
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With