1
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 is not defined

How can I set the variable and overwrite the value inside the mongoose query in order to return the value?

chichi
  • 2,777
  • 6
  • 28
  • 53

2 Answers2

1

You can just declare a variable using let above await and then use it in the findone callback

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

A more cleaner approach would be to assign the return value from await to addResult then use the values

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

You should explore a little more about variable scoping in javascript. There are a lot of resource available for example this What's the difference between using "let" and "var"?

Abhishek Sharma
  • 2,485
  • 1
  • 21
  • 35
1

You've got a bad mix of async and callbacks in your code there. Mongoose provides a promise-based API that works with await, so you can simply use that:

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

console.log(addResult);

return { sucess: true, addResult };
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Oh, just one minor question. What if there is an error? If I put that into `try-catch`, then I don't need to do like call back for error handling? thanks buddy – chichi May 04 '21 at 17:25
  • 1
    @GIHYUNNAM Yes, if you put this code in a try-catch, the `catch` should receive any error that occurs. – JLRishe May 04 '21 at 17:44