【问题标题】:Why mongoose is not awaiting for await new MODEL.save()为什么猫鼬不等待等待新的 MODEL.save()
【发布时间】:2022-12-18 11:07:55
【问题描述】:

我有 2 个服务器,其中一个工作正常,但第二个(第一个的修改变体)不是

`这是不工作:

router.post("/", async (req, res, next) => {
  const newBriefAppeal = await new BriefAppeal(req.body);
  let appealId;
  let target;
  let goals;
  let brand;
  let ***;
  try {
    const savedBriefAppeal = await newBriefAppeal.save(function (err, appeal) {
      appealId = appeal.id;
      target = appeal.step01target;
      goals = appeal.step02goals;
      brand = appeal.step03brand;
      *** = appeal.***
    });
    res.status(200).json(savedBriefAppeal);
  } catch (err) {
    res.status(500).json(err);
  }
});

` 我得到了错误

node:events:491
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read properties of undefined (reading 'id')

`但是我的类似项目中的这个变体工作正常:

router.post("/", async (req, res, next) => {
  const newAppeal = await new Appeal(req.body);
  let appealId;
  let name;
  let email;
  let phone;
  let subject;
  let message;
  let attachments = [];
  try {
    const savedAppeal = await newAppeal.save(function (err, appeal) {
      appealId = appeal.id;
      name = appeal.name;
      email = appeal.email;
      phone = appeal.phone;
      subject = appeal.subject;
      message = appeal.text;
      attachments = appeal.appealAttach.map((attachment) => ({
        filename: attachment,
        path: "./uploads/media/mailAttachments/" + attachment,
      }));
    });
    res.status(200).json(savedAppeal);
  } catch (err) {
    res.status(500).json(err);
  }
});

我哪里错了,为什么我的上诉是不确定的?

【问题讨论】:

    标签: javascript mongoose


    【解决方案1】:

    因为你正在传递一个回调。正如the documentation 中所说,save 仅当您返回承诺时传入一个回调。任何一个使用旧式回调签名或者使用承诺功能。

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 2019-03-20
      • 2019-11-12
      相关资源
      最近更新 更多