首页 > 解决方案 > 节点:使用猫鼬的 try-catch 中的全局变量

问题描述

try {
  globalThis.addResult;
  await game
    .collection("game")
    .findOne({ activity_id }, async (err, result) => {
      addResult = result;
    });
  console.log(`this - ${addResult}`);
  return { sucess: true, addResult };

ReferenceError:未定义 addResult

如何设置变量并覆盖 mongoose 查询中的值以返回值?

标签: javascriptnode.jsmongoose

解决方案


您的代码中的异步和回调混合不好。Mongoose 提供了一个基于 Promise 的 API,可以与 一起使用await,因此您可以简单地使用它:

const addResult = await game
    .collection("game")
    .findOne({ activity_id })
    .exec();

console.log(addResult);

return { sucess: true, addResult };

推荐阅读