Home > Software design >  Updating field value in a MongoDB document is turning string into object
Updating field value in a MongoDB document is turning string into object

Time:09-12

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.

CodePudding user response:

Problem

Every time you use as in TypeScript it means that something is wrong.

const name = req.body as string;

Your body isn't really a string, your body is the object:

{
  "string": ""
}

Solution

const { string: name } = req.body;

CodePudding user response:

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}}
  • Related