我的put方法复制代码而不是更新



我试图使用put方法在mongodb中存储用户数据。我的意图是更新这些数据,如果存在或创建新的。但我的方法创建新的数据,而不是更新…这段代码是从客户端(这里首先我上传我的图像到imgbb,然后我保存它到服务器)..

const image = data.image[0];

const formData = new FormData();

formData.append('image',image)

const API_KEY = '4957c3c668ded462db1fb1002c4535e6';
const url = `https://api.imgbb.com/1/upload?key=${API_KEY}`;
fetch(url,{
method : 'POST',
body : formData,
})
.then(res => res.json())
.then(result => {
if(result.success){
console.log('image',result.data.url)
const img = result.data.url;
const dataOfuser = {
user : user?.displayName,
email : user?.email,
phone: data.phone,
city: data.city,
education: data.education,
img: img
}
console.log(dataOfuser)
fetch(`http://localhost:5000/user/:${user.email}`,{
method:"PUT",
headers:{
'Content-Type': 'application/json'
},
body : JSON.stringify(dataOfuser)
})
.then(res => res.json())
.then(data => {
if(data.acknowledged){
toast.success('Profile Updated')
}
})
}
})
};

这些是mongodb的代码

app.put (/user/:电子邮件,异步(点播,res) =祝辞{

const email = req.params.email;

const user = req.body;

const filter = { email: email };

const options = { upsert: true };

const updateDoc = {

$set: user,

};

const result = await userCollection . updateOne ( filter , updateDoc , options);

res.send(result);

});

您可以尝试发送电子邮件和用户作为正文和

app.put("/user/email", async (req, res) => {
const { dataOfuser } = req.body; //this finds all
const { email, user, phone, city, etc} = dataOfuser; //this extracts the values, but probably better to send each values by themselves

你也可以单独发送用户和电子邮件等,而不是作为一个对象:

body: JSON.stringify({ user, email, phone, city, education, img })

您也可以尝试在body: JSON中的dataOfuser周围添加花括号。stringify({dataOfuser})


const res = await userCollection
.updateOne(
{ email: email} *find the user by his email*
{ $set: {email: email, phone: phone, city: city etc.}}) *set email to email from body*
})

您还应该在输入中使用默认值作为其当前值,因此字段不会被覆盖为null或空白

最新更新