Updating field value in a MongoDB document is turning string into object

Issue

I am currently making a project using React TypeScript, MongoDB, and Express.js. I am trying to update the field value in my MongoDB document, and it is supposed to be a string, but instead it is automatically turning it into an object. Has anyone had that problem before? If so, how did you fix it?

How it’s supposed to be:

character_name: "string"

How it’s updating:

character_name: {
     "string": ""
}

I’ve even logged it in the console to show me the type of data, and it’s saying it’s a string, so I don’t know what it could be doing?

The backend routes:

routes.put("/change-name", async (req, res) => {

const name = req.body as string;

try {
    const client = await getClient();
    const result = await client.db().collection<Account>('accounts').updateOne({ username: "AndrewDamas" }, {$set: {character_name: name}});
    if (result.modifiedCount === 0) {
        res.status(404).json({ message: "Not Found" });
    } else {
        res.json(name);
    }
} catch (err) {
    console.error("FAIL", err);
    res.status(500).json({ message: "Internal Server Error" });
}
});

The service code on the frontend side:

export function changeName(name: string){
     return axios.put(`${baseUrl}/change-name`, name)
     .then(res => res.data);
}

And how I used it in my code:

function saveData(){
     console.log(ourCharacterName);
     changeName(ourCharacterName);
}

Any help would be greatly appreciated! Thanks.

Solution

Put request. When sending data as body, it’s going to arrive as json in your server . So you can either deconstruct it or use dot notation in your route method.

return axios.put(`${baseUrl}/change-name`, {name:name})

Deconstruct the variable from the body

const {name} = req.body;

Update the document

... {$set: {character_name: name}}

Answered By – Ryan Zeelie

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published