Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map object to mongoose model

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;
...
like image 613
tommyd456 Avatar asked Oct 21 '25 12:10

tommyd456


1 Answers

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){
  ...
});
like image 136
Jason Cust Avatar answered Oct 23 '25 02:10

Jason Cust