Home > Blockchain >  Why mongoose is not awaiting for await new MODEL.save()
Why mongoose is not awaiting for await new MODEL.save()

Time:12-08

I have 2 servers and one of these is work fine, but second (modified variant of first) is not

`This is not works:

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);
  }
});

` and i got error

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

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

`but this variant in my similar project works fine:

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);
  }
});

Where's i'm wrong and why my appeal is undefined ?

CodePudding user response:

Because you're passing in a callback. As it says in the documentation, save only returns a promise when you don't pass in a callback:

Returns:

...Returns undefined if used with callback or a Promise otherwise.

Either use the old-style callback signature or use the promise feature.

  • Related