Sending data via ajax generating new "_id" in Mongodb

Asked

Viewed 38 times

0

I am sending information via ajax to the backend in Node to update a document in Mongodb, but whenever I send the form via frontend, it generates a new "_id" instead of searching for an existing one as I am trying to do. Follows the code:

**OBS.: **I tested in Insomnia (similar to Postman), and by then it has worked

Section of the frontend where I send the form data

document.querySelector('#update').addEventListener(
    'click', 
    (
        ev, 
        url = '/admin/user/update', 
        data = {
            _id: userId, 
            email: document.querySelector('#email').value, 
            name: document.querySelector('#name').value, 
            userType: document.querySelector('#userType').value
        }, 
        success 
    ) => {

    success = (data) => {console.log(data)};
    console.log('===> response id', userId)
    let params = typeof data == 'string' ? data : Object.keys(data).map(
            function(k){ return `${k}:${data[k]}` }
        ).join(',');


    let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    console.log('url =====> ', url);
    xhr.open('put', url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }
    };
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    let obj = new Object();

    params.split(',').forEach(element => {

        element = element.split(':')

        var name = element[0]
        var value = element[1]

        obj[name] = value

    });
    //console.log(obj)
    obj = JSON.stringify(obj);
    console.log('===>obj', obj)
    console.log('===>obj', obj.toString())

    xhr.send(obj);
    return xhr;
});

Excerpt in the backend treating this call

router.put('/user/update', async (req, res) => {

    let { _id, email, name, userType} = req.body;

    console.log('user/id =============>',  ObjectID(_id)); 
    
    console.log('req.body ======> ', req.body);

    try { 
        const user = await User.findOne(ObjectID(_id));
        console.log('User id ======> ', user._id);
        
        if( user ){
 
            console.log('User ======> ', user)

            console.log('email, name, userType =====> ', email, name, userType)

            console.log('ObjectID(user._id) ======> ', ObjectID(user._id))

            let updateUser = await User.updateOne({_id}, {$set:{ email, name, userType }});
            if(updateUser)  {
                console.log('===> updated', updateUser);
                console.log('User 2 ======> ', user)
                let message = "Usuario Editado com sucesso";
                console.log(message) 
    
                return res
                    .status(400)
                    .render(path.resolve('../frontend/views/layouts/admin/cadastroUsuario'), {message});
    
            }

            // if(update){
                
            //     let message = "Usuario Editado com sucesso";

            //     return res
            //         .status(400)
            //         .render(path.resolve('../frontend/views/layouts/admin/cadastroUsuario'), {message});
            // }

        }
        
    } catch (err){

        return res.status(400).send({error: 'Update failed: ' + err });
    }
});

Example of Return via frontend:

user/id =======> 5df4932bfc08782574c9cf56
req.body => {'{"_id":"5de9cc215f40d1626cabe9c9"
   ,"email":"[email protected]","name":"Vitor 
   TE22STE","userType":"adminNv2"}': ''
 }

1 answer

0


Apparently you are mixing the string and objectid types in _id.

Barter let updateUser = await User.updateOne({_id}, {$set:{ email, name, userType }});

for let updateUser = await User.updateOne(ObjectId(_id), {$set:{ email, name, userType }});

should solve.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.