0

First of all, forgive me about the title couldn't think of an appropriate title.

const product = products.findOne({_id}, (error, productFound) => {
    console.log(productFound.name);
        return {...productFound};
});

console.log(product.name);

the log inside findOne method do return me a true value, but the log outside the findOne function returns undefined.

why is that and how can I get the data outside the findOne function?

Kadiem Alqazzaz
  • 554
  • 1
  • 7
  • 22
  • 1
    You are misunderstanding how callback works – Orelsanpls May 23 '19 at 13:21
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – VLAZ May 23 '19 at 13:22

2 Answers2

0

Because findOne does not return its value to the assignment in your case. you have to assign the callback result to outer value. But in this case, latest console.log statement has already been evaluated.

you can use async/await style for better reading here

scetiner
  • 361
  • 3
  • 9
0

after reading the comments and studying Async/Await for a little bit here is the final code I ended up with:

function getProduct() {
    return new Promise((resolve, reject) => {
        resolve(products.findOne({_id}, (error, productFound) => {
            return {...productFound};
        }))
    })
}

const product = await getProduct();

console.log(product.name);
Kadiem Alqazzaz
  • 554
  • 1
  • 7
  • 22