1

I am working on nodejs and i am using "Express js" framework, I am working on Controller and i am trying to get data from "two model functions" but i am getting message "anonymous", How can i get data from multiple "model functions", Here is my code,

  • This is my homeController
homeController.index = function (req, res, next) {
  // fetching data into 'data variable' from FetchRecords model
  homeModel.FetchRecords(function (err, data) {
    if (err) {
      req.flash('error', 'There was no records.');
    } else {
      res.render('home/index', { data: data });
    }
  });

  homeModel.getAverage(function (average) {
    console.log(average);
    // res.render('home/index',{data:average});
  });
};
  • This is my homeMOdel
homeModel.FetchRecords = function (data) {
  sql.query('SELECT * FROM rating', function (err, res) {
    if (err) {
      return data(err, null);
    } else {
      return data(null, res);
    }
  });
};

homeModel.getAverage = function (average) {
  console.log(average);
  sql.query('SELECT avg(value) FROM rating', function (err, res) {
    if (err) {
      return average(err, null);
    } else {
      return average(null, res);
    }
  });
};
1
  • Call homeModel.getAverage before res.render('home/index' line. Commented Apr 1, 2022 at 8:12

1 Answer 1

1

Inside homeModel just create 1 function instead of 2 separate. You can combine both MySQL queries into one like this.

const FetchRecordsAndAverage = function (data) {
      sql.query('SELECT * FROM rating; SELECT avg(value) FROM rating', function (err, res) {
        if (err) {
          return data(err, null);
        } else {
          return data(null, res);
        }
      });
    };

module.exports = { 
    FetchRecordsAndAverage
}

With this you will get combined data of both queries as arrays inside array. Result of queries can be accessed as data[0] & data[1].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.