node.js - 由于缺少引号,布尔值未在 MERN 堆栈中更新
问题描述
我正在使用MERN堆栈创建一个日志记录 Web 应用程序。所有功能都运行良好,只有一个问题:当我尝试更新日志时,所有内容都会更新(消息、技术员、日期),只是一个布尔实体(注意)没有更新。
我尝试了很多事情,在邮递员中,我开始意识到 - 消息、技术人员和日期是在引号内提交的( "message","tech_name","10/11/2001" )。只是布尔实体 - 注意提交时不带引号(true)。
以下是转发到 API 的数据:
由于注意力有一个布尔数据类型,它只是true 或 false,而不是"true" 或 "false"
因此,当我使用邮递员提交数据时,在布尔值中添加引号,它就起作用了!. 我只是不知道如何在编码中使用 MERN。任何帮助,将不胜感激。这是邮递员中带引号和不带引号的提交图像。
我正在使用 MERN(Mongoose、Express、React 和 Node)。我在这里粘贴了一些相关代码。如果需要我的代码的任何其他部分,请发表评论。
//注意力的初始化
const [attention, setAttention] = useState(false);
// 更新日志的方法
const updLog = {
id: current._id,
message,
tech,
attention,
date: new Date(),
};
updateLog(updLog);
// 更新日志动作
export const updateLog = (log) => async (dispatch) => {
try {
setLoading();
const res = await fetch(`/logs/${log.id}`, {
method: "PUT",
body: JSON.stringify(log),
headers: {
"Content-Type": "application/json",
},
});
const data = await res.json();
console.log(data);
dispatch({
type: UPDATE_LOG,
payload: data,
});
clearCurrent();
} catch (err) {
dispatch({
type: LOGS_ERROR,
payload: err.response.statusText,
});
}
};
// 后端更新路由
router.put("/:_id", async (req, res) => {
const { message, tech, attention, date } = req.body;
const logFields = {};
if (message) logFields.message = message;
if (tech) logFields.tech = tech;
if (attention) logFields.attention = attention;
if (date) logFields.date = date;
try {
let log = await Logs.findById(req.params._id);
if (!log) return res.status(404).json({ msg: "Log Not Found" });
log = await Logs.findByIdAndUpdate(
req.params._id,
{
$set: logFields,
},
{
new: true,
}
);
res.json(log);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
(看看这个看看发生了什么:https ://gifyu.com/image/GGi6 )
解决方案
您当然可以将客户端更改为始终将注意力字段作为字符串发送
const updLog = {
id: current._id,
message,
tech,
attention: attention ? "true" : "false",
date: new Date(),
};
updateLog(updLog);
但是您真正的问题在于以下行:
if (attention) logFields.attention = attention;
如果设置了注意字段并且为 true,则if (attention)
only 评估为true - 如果您只想检查注意字段是否为undefined
or null
,请将变量与null
instead 进行比较(当值未定义时也会捕获。来源):
if (attention != null) logFields.attention = attention;
要预先测试我是否正确识别了问题,请尝试使用邮递员通过传递布尔值将注意力值从 更改为false
-它应该可以工作。true
只是不是相反,因为logFields.attention
从不设置 whenattention
不是一个真实的值。
推荐阅读
- python - 尝试使用词袋概念生成特征列并合并到现有数据框
- python - 具有时间序列数据/行到列/重新组织数据到单行的数据透视表
- java - Spring webflux:在响应式请求处理的整个过程中保持 EntityManager 打开
- c# - 如何计算金额的间接费用
- javascript - 如何将事件从父级传递给子级以与功能组件做出反应?
- pouchdb - PouchDB 强制更新
- bash - 将格式化的日期行输出打印到 Bash 脚本中的文件
- javascript - 在 Node 中使用 googleapis 包交换访问令牌的授权码
- android - Xamarin Android:当ai点击recyclerview项目时如何从mainactivity中隐藏项目
- ios - 设置不同颜色的 UISlider 角的 setMinimumTrackImage