首页 > 解决方案 > 由于缺少引号,布尔值未在 MERN 堆栈中更新

问题描述

我正在使用MERN堆栈创建一个日志记录 Web 应用程序。所有功能都运行良好,只有一个问题:当我尝试更新日志时,所有内容都会更新(消息、技术员、日期),只是一个布尔实体(注意)没有更新。

日志字段

我尝试了很多事情,在邮递员中,我开始意识到 - 消息、技术人员和日期是在引号内提交的( "message","tech_name","10/11/2001" )。只是布尔实体 - 注意提交时不带引号(true)。

以下是转发到 API 的数据:

控制台日志

由于注意力有一个布尔数据类型,它只是true 或 false,而不是"true" 或 "false"

因此,当我使用邮递员提交数据时,在布尔值中添加引号,它就起作用了!. 我只是不知道如何在编码中使用 MERN。任何帮助,将不胜感激。这是邮递员中带引号和不带引号的提交图像。

不带引号提交:: 不带引号提交

带引号提交((当我将引号添加到 false 时更新):: 提交报价

我正在使用 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 )

标签: node.jsreactjsexpressmongooseboolean

解决方案


您当然可以将客户端更改为始终将注意力字段作为字符串发送

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 - 如果您只想检查注意字段是否为undefinedor null,请将变量与nullinstead 进行比较(当值未定义时也会捕获。来源):

if (attention != null) logFields.attention = attention;

要预先测试我是否正确识别了问题,请尝试使用邮递员通过传递布尔值将注意力值从 更改为false-它应该可以工作。true只是不是相反,因为logFields.attention从不设置 whenattention不是一个真实的值。


推荐阅读