dhana lakshmi dhana lakshmi - 16 days ago 8
Node.js Question

nodejs post method is not saving data

i have post method which is working fine when i do as shown below

var companyDetailsModel = mongoose.model('companyDetails')
router.post('/companyDetails', function(req, res, next) {
var newCompanyDetails = new companyDetailsModel();

newCompanyDetails.companyName=req.body.companyName;
newCompanyDetails.streetAddress=req.body.streetAddress;
newCompanyDetails.city=req.body.city;
newCompanyDetails.Street=req.body.Street;
newCompanyDetails.ZipCode=req.body.ZipCode;
newCompanyDetails.Phone=req.body.Phone;
newCompanyDetails.Fax=req.body.Fax;
newCompanyDetails.webSite=req.body.webSite;
newCompanyDetails.Logo=req.body.Logo;

newCompanyDetails.save(function(err) {
if (err){
console.log('Error in Saving user: '+err);
}
console.log('User Registration succesful');
res.send("user added sucessfully");
});

})


this route works fine and data is saved in the database but if i try to do it as shown below

router.post('/companyDetails', function(req, res, next) {
var newCompanyDetails = new companyDetailsModel();
newCompanyDetails= req.body;
newCompanyDetails.save(function(err) {
if (err){
console.log('Error in Saving user: '+err);
}
console.log('User Registration succesful');
res.send("user added sucessfully");
});

})


i will get internal server error like newCompanyDetails.save is not a function please say why is this behavior if a post request contains 100 of fields should i explicitly should i assign all the fields please help me understand this

Answer

you erase mongo object with this line

newCompanyDetails= req.body;

Do this instead :

 var newCompanyDetails = new companyDetailsModel(req.body);