由于缺少引号,布尔值未在 MERN 堆栈中更新

Boolean Value is not getting updated in MERN stack due to lack of quotation marks

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

我尝试了很多东西,在邮递员中,我开始意识到 - 消息、技术人员和日期在 引号 内提交(“消息”,“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

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

const updLog = {
 id: current._id,
 message,
 tech,
 attention: attention ? "true" : "false",
 date: new Date(),
 };
updateLog(updLog);

但您真正的问题在于以下行:

if (attention) logFields.attention = attention;

如果注意力字段设置 和 trueif (attention) 仅评估为真 - 如果您只想检查注意力字段是否为 undefinednull,将变量与 null 进行比较(当值未定义时也会捕获。Source):

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

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