Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

68
Visualizações
my put method duplicate the code insteade of updating

i am trying to store user data in mongodb using put method .my intension is to update those data if there exist or create new. but my method create new data insteade of updating.. this code is from client side(here first i uploaded my image to the imgbb then i save it to server).. .

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')
                }
            })
        }
    })
};

these are the code from mongodb

app.put('/user/: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);
      
      });
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could try to send email and user as body and

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

You can also just send user and email etc on their own, instead of as one object:

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

You can also try to add curlybraces around dataOfuser in the body: 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*
})

You should also have default value in inputs as their current value, so the fields doesn't get overwritten as null or blank

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda