我的节点是js代码,
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);
});
};
从上面我只给出了2个(名字,姓氏)字段,但剩下的字段(phone.street)被分配了空值。有人帮我解决问题。
答案 0 :(得分:1)
你可能想检查然后设置值,这只是从前端发送的设置值,如
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);
});
};
答案 1 :(得分:0)
您的代码中的一切都很好。但您需要确保变量项目中存在电话,街道字段。因为您的唯一给名字&来自参数的姓氏。如果您没有将价值提供给电话& 街道(通过参数)请从项变量中删除该字段。
尝试以下代码,让我知道它的返回值
exports.updateprofiledetails = function (req, res) {
console.log(req.body)
var params = req.body;
var item =
{
firstname:params.firstname,
lastname:params.lastname
};
console.log(item) // Ensure this variable have data
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);
});
};