0

I'm trying to initialize a variable x to the value returned by the showData function. Here's my code:

app.post("/view/show", (req,res) => {
    let x = showData(req.body.custmerName);
    console.log(x);
}

And here is the showData function:

const showData = (custName) => {
    const customer = mongoose.model(custName ,collectionSchema,custName);
    customer.find( (error,data) => {
        if (error){
            console.log(error);
        }else{
            return data;  
        }
    });
}

However, the console shows undefined. If I add console.log(data) to the showData function, I can see that I was able to successfully fetch data from the database.

I understand that console.log(x) is not waiting for the execution of showData(), due to the synchronous property of JavaScript. How can I get the value from the function and log it to the console, instead of getting undefined?

Donut
  • 110,061
  • 20
  • 134
  • 146
VELDAS R DURAI
  • 301
  • 4
  • 9
  • Hi, welcome to Stack Overflow. Many, _many_ similar questions have been asked already. Search SO for "javascript async undefined" and you'll be able to find your answer. Here's one https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call. – Avius Oct 27 '20 at 17:50

3 Answers3

1

You can use async/await or callback when dealing with the async functions.

app.post("/view/show", (req,res) => {
  showData(req.body.custmerName, (err, res) => {
    const x = res;
    console.log(x);
  });
});

const showData = (custName, callback) => {
  const customer = mongoose.model(custName ,collectionSchema,custName);
  customer.find(callback);
}
Rinkesh Golwala
  • 979
  • 1
  • 7
  • 17
  • 1
    @VELDASRDURAI if this answer solved your problem, it would be good if you accepted it. – Avius Oct 31 '20 at 10:20
0

I haven't actually used Mongoose before, but looking at the docs, there doesn't seem to be a version of the find function that just takes a callback function.

Try passing the query object also (in your case, an empty object should suffice):

customer.find({}, (error,data) => {
    if (error) {
        console.log(error);
    } else {
        return data;  
    }
});

From the docs:

// find all documents
await MyModel.find({});

// find all documents named john and at least 18
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();

// passing options
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();
Ibz
  • 437
  • 2
  • 7
-1

You need an asynchronous function to do that. Do the following:

app.post("/view/show", async(req,res) => {
    let x = await showData(req.body.custmerName);
    console.log(x);
}
M4RCKIT0S
  • 25
  • 1
  • 7