等待findOneAndUpdate不等待

时间:2019-12-04 05:27:39

标签: node.js mongodb mongoose

我有一个功能,我需要带一些ID来使用acyn并等待,以便在findOneAndUpdate即时消息上填充更新,但是findoneandupdate在其他代码之前运行...不知道为什么

async function update(req, res) {
    const update = req.body;

    await Something1.findOne({
        'id_Something1': update.something1_id
    }).exec((err, something) => {
        if (err || !something) {
            return res.status(500).send({
                message: 'Error'
            })
        }
        update.something1= something._id;
    });


    await Collection.findOneAndUpdate({
        'id_something1': update.custom_id
    }, update, (err, Updated) => {
        console.log('this should show after the first find but it doesnt');
        if (err) {
            return res.status(500).send({
                error: err.errmsg
            });
        } else if (!sociosUpdated) {
            return res.status(500).send({
                message: 'Error'
            });
        }
        res.status(200).send({
            data_updated: Updated
        });
    });
};

1 个答案:

答案 0 :(得分:1)

问题是您同时使用async/awaitasynchronous。您可以尝试以下代码:

async function update(req, res) {
   const update = req.body;

   try {
      const something =  await Something1.findOne({
          'id_Something1': update.something1_id
        }).exec();

      update.something1 = something && something._id;

      const Updated = await Collection.findOneAndUpdate({
        'id_something1': update.custom_id
      }).exec();

      return res.status(200).send({
        data_updated: Updated
      });
   }
   catch(err) {
       return res.status(400).send(err);
   } 
 });