如何避免多次Mongoose操作的嵌套承诺?

安托

对不起,我知道NodeJS中已经有很多帖子讨论嵌套承诺问题,但是我仍然无法弄清楚这一点。
我正在使用Express和Mongoose,我想找到一个对象ID,然后保存一个对象,然后更新另一个对象,但是我不知道该怎么做,因为这些都是依赖的承诺:

        // Get Client object ID from email
        Client.findOne({ email: req.body.clientEmail })
          .exec()
          .then((client) => {
            // Then add Client ID to program and save
            const program = new Program(req.body);
            program.Client = client._id;
            program.save()
              // Finally add the program to the existing coach user
              .then((program) => {
                Coach.updateOne({ _id: req.session.userId }, { $push: { programs: program._id } },
                  function (err, coachUpdated) {
                    if (err) return handleError(err);
                    console.log(coachUpdated);
                  })
              })
              .then(() => { res.send('New program added!'); });
          })

提前致谢

Sulabh singla

随着异步/等待。使用try / catch块。

async function findClientAndUpdateCoach(req, res) {
    try {
        const client = await Client.findOne({ email: req.body.clientEmail }).exec();

        const program = new Program(req.body);
        program.client = client._id;
        const result = await program.save() // Must be asynchronous in nature to prevent blocking..

        Coach.updateOne({ _id: req.session.userId }, { $push: { programs: program._id } },
            function (err, coachUpdated) {
                if (err) return handleError(err);
                console.log(coachUpdated);
                res.send('New program added!');
            });
    }
    catch (err) {
        return handleError(err);
    }

    findClientAndUpdateCoach(req, res);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章