简体   繁体   English

更新 MongoDB 文档中的字段值正在将字符串转换为 object

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

I am currently making a project using React TypeScript, MongoDB, and Express.js.我目前正在使用 React TypeScript、MongoDB 和 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.我正在尝试更新我的 MongoDB 文档中的字段值,它应该是一个字符串,但它会自动将其转换为 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.谢谢。

Problem问题

Every time you use as in TypeScript it means that something is wrong.每次使用as时,都意味着出现问题。

const name = req.body as string;

Your body isn't really a string , your body is the object:你的身体不是真正的string ,你的身体是 object:

{
  "string": ""
}

Solution解决方案

const { string: name } = req.body;

Put request.提出请求。 When sending data as body, it's going to arrive as json in your server.当以正文形式发送数据时,它将以 json 的形式到达您的服务器中。 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}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM