Home > Back-end >  How to send data from model to controller node js
How to send data from model to controller node js

Time:05-31

I am calling getIndex function in contoller from routes and fetchAll from model is getting data from database but how to store the data and send it to contoller and how to receive in contoller.

This is how i have connected the database

const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'practice',
password: ''
});
module.exports = pool.promise();

model

const db = require('../database');

module.exports = class User {   
fetchAll(){
     db.execute('SELECT * FROM users')
     .then(([rows,fieldData]) => {
         console.log(rows); //giving the required data
      })
}
}

controller

const User = require('../model/user');

exports.getIndex = (req,res,next) => {
const user = new User();
user.fetchAll();
res.render('index');
};

CodePudding user response:

here is a good example of where to use promises and async/await

in modal do this

const db = require('../database');

module.exports = class User {
    fetchAll() {
        return (new Promise((resolve, reject) => {
            db.execute('SELECT * FROM users')
                .then(([rows, fieldData]) => {
                    resolve(rows); // return data
                })
        }))

    }
}

in the controller do this

const User = require('../model/user');

exports.getIndex = async (req, res, next) => {
    const user = new User();
    let data = await user.fetchAll();
    res.render('index');
};
  • Related