【问题标题】:mongoose not saving my array after save()mongoose 在 save() 之后没有保存我的数组
【发布时间】:2021-01-03 08:28:07
【问题描述】:

所以我有以下类型的模式:

board: {
id:
createdBy:
boardlist: [
{id, title: list1, cards: []}
{id, title: list2, cards: []}
]

我想在特定列表 id 的卡片数组中推送一张卡片

这是我的代码:

router.put("/add-card/:id", auth, boardAuth, async (req, res) => {
  const listId = req.params.id;

  const board = await Board.findOne({ _id: req.board._id });
  if (!board) return res.status(404).send("no such board");

  const list = await List.findOne({ _id: listId });
  if (!list) return res.status(404).send("List not found");

  const card = new Card({
    text: req.body.text,
  });

  list.cards.push(task);

  board.boardLists.map((list) => {
    if (listId.toString() === list._id.toString()) {
      list.cards.push(card);
    } else {
      null;
    }
  });
  await board.save();
  await list.save();
  res.send(board);
});

问题是,当我这样做时,它会一次将卡添加到该阵列中,而在下一次我这样做时,它就消失了,并用新的替换了旧的。 如果我推卡“一”,它会在我发送时出现在数组中,而在下一次我推“二”时,我看不到最后一个“一”,看起来我只有 1 个项目。

【问题讨论】:

    标签: node.js reactjs express mongoose


    【解决方案1】:

    您是否在控制台中收到错误消息?我建议你做一个try/catch 块,这样我们就可以捕获错误和所有错误。

    try {
      const board = await Board.findOne({ _id: req.board._id });
        if (!board) return res.status(404).send("no such board");
    
        const list = await List.findOne({ _id: listId });
        if (!list) return res.status(404).send("List not found");
    
        const card = new Card({
          text: req.body.text,
        });
    
        list.cards.push(task);
    
        board.boardLists.map((list) => {
          if (listId.toString() === list._id.toString()) {
            list.cards.push(card);
          } else {
            null;
          }
        });
        await board.save();
        await list.save();
        res.send(board);
    } catch (err) {
      console.log(err);
    }
    

    【讨论】:

    • 我没有收到任何错误。该卡只添加到数组中一次,然后如果我添加一张新卡,我看不到最后一张……总是有 0 或 1 张卡
    • 有人知道吗?
    • 也许你应该检查你的模型。如果为 0 或 1,则为模型验证问题。
    猜你喜欢
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2020-12-01
    • 2013-12-04
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多