node.js - 如何避免多个 Mongoose 操作的嵌套 promise ?

标签 node.js express mongoose promise nested

很抱歉,我知道已经有一些帖子处理 NodeJS 中的嵌套 Promise 问题,但我仍然无法弄清楚这个。
我正在使用 Express 和 Mongoose,我想找到一个对象 ID,然后保存一个对象,然后更新另一个对象,但我不明白我应该如何做得更好,因为这些是依赖的 promise :

        // 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!'); });
          })

提前致谢

最佳答案

与异步/等待一起。使用 try/catch block 。

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

关于node.js - 如何避免多个 Mongoose 操作的嵌套 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58390124/

相关文章:

javascript - WebRTC 视频 session (多对多)

javascript - 如果消息仅以标签开头,如何让 slackbot 回复

node.js - 如何在 api 路由中使用多个函数?

javascript - PromisifyAll - 回调不是函数

javascript - MongoDB 对填充字段的查询

javascript - 递归未超过第一级

node.js - Typescript 接口(interface)[] 与 [接口(interface)]

javascript - 使用 Express-ip-filter 只允许同一网络上的计算机

javascript - 为 Node.js 中的链式函数编写 Jest 测试

node.js - 蒙哥错误: Econnrefused