【问题标题】:findOneAndUpdate updates database but hangsfindOneAndUpdate 更新数据库但挂起
【发布时间】:2020-05-29 04:42:55
【问题描述】:

问题:我的异步函数确实更新了数据库,但没有继续执行脚本的其余部分。

//Process the data after you get it...
async function burnStatus(data) {
  console.log("Burn Data Compiled Saving...");

  let filter = { _id: "5e4454059a0be1c238b5f70b" };

  if (data.error === true) {
    console.log("Error retrieving burn data.");

    var update = { update: burn.date, error: data.error };
  } else {
    var update = {
      date: data.date,
      precipitation: data.precipitation,
      wind: { morning: data.wind.morning, afternoon: data.wind.afternoon },
      ventIndex: data.ventIndex,
      aqi: data.aqi,
      updated: data.updated
    };
  }

  console.log(update);

  let doc = await BURN.findOneAndUpdate(filter, update, { upsert: true }, (error, result) => {
    // *** NOTHING BELOW HERE EXECUTES EVEN THOUGH THE DB DOES GET UPDATED. ***

    if (error) {
      console.log(error);
    } else {
      console.log(result);
    }
  });

  console.log("Burn Data Updated");
}

这是输出:

Getting Burn Data...
(node:16248) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Response Received Processing...
Precipitation: 0
Morning Wind: 6
Afternoon Wind: 8
Ventilation Index: POOR
AQI: 48
Burn Data Compiled Saving...
{
  date: '02/13/20',
  precipitation: 0,
  wind: { morning: 6, afternoon: 8 },
  ventIndex: 'POOR',
  aqi: 48,
  updated: '2020-02-13T12:42:11.201Z'
}

疑难解答:

我已设法将其追踪到let doc = await BURN.findOneAndUpdate(filter, update, (error, result) => { 行。我无法让它抛出一个错误让我捕捉(或者我没有尝试正确捕捉错误)。

所以我猜没有错误,我只是做错了。

【问题讨论】:

  • 我还建议阅读callbackspromisesawait 之间的区别。从长远来看,它将对您有很大帮助。

标签: node.js mongodb asynchronous mongoose


【解决方案1】:

您同时使用await 和这里的回调(error, result)

你需要选择一个而不是两个。

等待

try {
  let result = await BURN.findOneAndUpdate(filter, update, {upsert: true});
  console.log("Burn Data Updated")
} catch (error) {
  console.log(error)
}

回调

let doc = BURN.findOneAndUpdate(
  filter,
  update,
  { upsert: true },
  (error, result) => {
    if (error) {
      console.log(error);
    } else {
      console.log(result);
      console.log("Burn Data Updated");
    }
  }
);

【讨论】:

  • 杰克,谢谢你的帮助。我仍然有同样的问题。最初我刚刚等待,我添加了回调以尝试捕获错误。 (这显然是错误的方式)。从那以后我改成了:``` try { let result = await BURN.findOneAndUpdate(filter, update, {upsert: true}); console.log("Burn Data Updated") } catch (error) { console.log(error) } ``` 它仍然没有记录“Burn Data Updated”或产生错误。
  • 忽略我的最后一次,我相信我已经弄清楚了。我试图将此作为一个模块进行故障排除,并且将它与我的 app.js 分开加载,即使我的 app.js 仍在后台运行。我重新启动了 app.js,它完成了整个功能。再次感谢您的帮助。
猜你喜欢
  • 2020-01-13
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 2019-04-19
  • 1970-01-01
  • 2017-05-01
  • 1970-01-01
相关资源
最近更新 更多