klp klp - 2 months ago 7
Node.js Question

How to update records in mongo db using node js

My node js code,

exports.updateprofiledetails = function (req, res) {
console.log(req.body)
var params = req.body;
var item =
{
firstname:params.firstname,
lastname:params.lastname,
phone:params.phone,
street:params.street
};console.log(item)
var id = req.params.id;
var record= db.collection('profile');
record.updateOne({'_id':id},{$set:item},(err, result) => {
if (err){ return console.log(err)
}
if(result){
response = {status:'success',data:result};
} else{
response = {status:'fail',data:[]};
}
res.send(response);
});

};


From the above i give only 2(firstname,lastname) fields but then the remaining fields(phone.street) are assigned with null values.Can someone help me solve the problem.

Answer

You may like to check and then set value that is only set value which sent from front end like

exports.updateprofiledetails = function (req, res) {
  console.log(req.body)
  var params = req.body;
  var item = { }
  if(params.firstname)
    item.firstname = params.firstname;
  if(params.lastname)
    item.lastname = params.lastname;
  if(params.phone)
    item.phone = params.phone;
  if(params.street)
    item.street = params.street;
  console.log(item);
  var id = req.params.id;
  var record= db.collection('profile');
  record.updateOne({'_id':id},{$set:item},(err, result) => {
   if (err) { 
     return console.log(err)
   }
   if(result){
      response = {status:'success',data:result};
   } else{
      response = {status:'fail',data:[]};
   }
   res.send(response);
  });
};
Comments