I POST
a user object to my backend and I would like to be able to save this user directly to my database using Mongoose.
However, if I assign a new model with an object, it overwrites the save method.
e.g.
var user = new User();
user = req.body.user //save no longer available
user.save(function(err){
...
}
Is there a way to overcome this as at the moment I am having to assign each field for the user to the model like so:
var user = new User();
user.email = req.body.user.email;
user.name = req.body.user.name;
...
You are reassigning the variable user
with the req.body.user
value so the new model you originally assigned is discarded.
var foo = 'first'; // declares foo and assigns 'first' to it
foo = 'second'; // reassigns foo with value 'second'
var user = new User(); // declares user and assigns a new User model instance
user = req.body.user // reassigns user with value from req.body.user
You can pass the value to the User model constructor and this would achieve your desired result:
var user = new User(req.body.user); // declares user and assigns a new User model with req.body.user as the initial value
user.save(function(err){
...
});
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