How can we call 2 models in one controller in Node Express JS...?

Viewed 125

I am new in Nodejs and I am using express JS framework with MVC pattern I want to get data from two different tables (with use of two different functions in model) in single controller function, Can I do this ?

  1. How can I pass parameters to two different model
  2. How can we manage result/response from two different model ?

-- Here is my Model

sensorModel.getAllSensorSite=function(result){
    sql.query("SELECT * FROM site",function(err,res){
        if(err) {
            return result(err,null);
        }
        else{
         return result(null,res);
        }
    });
}

sensorModel.getAllSensorRowss=function(result){
    sql.query("SELECT * FROM rowss",function(err,res){
        if(err) {
            return result(err,null);
        }
        else{
         return result(null,res);
        }
    });
}

-- Here is my Controller

sensorController.index=function(req,res,next){
    sensorModel.getAllSensorSite(function(err,site){
        if(err){
                throw err;
        }else{
            res.json({ site });
        }       
    });
}
1 Answers

Using this method, you're sending queries to database but you can't wait for their reply. I would recommend to use bluebird to be able to wait for database responses or to use an ORM (like sequelize) along with await/async

Related