Estoy tratando de almacenar datos de usuario en mongodb usando el método put. Mi intención es actualizar esos datos si existen o crear nuevos. pero mi método crea nuevos datos en lugar de actualizar ... este código es del lado del cliente (aquí primero cargué mi imagen en imgbb y luego la guardo en el servidor) .. .
const imagen = datos.imagen[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') } }) } }) };estos son los codigos de mongodb
app.put('/usuario/:email',async(req,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); });Podría intentar enviar correo electrónico y usuario como cuerpo y
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 themselvesTambién puede enviar el usuario y el correo electrónico, etc. por sí solos, en lugar de como un solo objeto:
body: JSON.stringify({ user, email, phone, city, education, img })También puede intentar agregar llaves alrededor de dataOfuser en el cuerpo: JSON.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* })También debe tener un valor predeterminado en las entradas como su valor actual, para que los campos no se sobrescriban como nulos o en blanco.