node.js - findOneAndUpdate 更新数据库但挂起

标签 node.js mongodb asynchronous mongoose

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

//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 = wait BURN.findOneAndUpdate(filter, update, (error, result) => { 行。我无法让它抛出一个我要捕获的错误(或者我没有尝试正确捕获错误)。

所以我猜没有错误,我只是做错了一些事情。

最佳答案

您在此处同时使用了 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");
    }
  }
);

关于node.js - findOneAndUpdate 更新数据库但挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60208425/

相关文章:

node.js - 使用 Mongoose 统一错误捕获

javascript - 在 Selenium WebDriver 中使用 execute_async_script

json - 在 Heroku 上使用 Node 读取、写入和存储 JSON

.net - 为什么 SynchronizationContext 不能正常工作?

c# - 使用 Task.Run 而不是 Delegate.BeginInvoke

node.js - 忽略调试器;调试 session 期间 Node.js 中的语句

node.js - 使用 Git Deploy 将 Ghost 0.4.2 部署到 Azure 站点

javascript - 从javascript中的回调函数返回值?

javascript - 如何在严格模式下获取函数名称[正确方式]

mongodb - 在没有 $ 运算符的情况下使用 mongodb 中的子数组元素更新多个文档