Hi, I am trying to build an MVC model API. I'm having troubles making queries. It seems like I don't export my connection variable correctly, cause I've got a "connection.query is not a function" error.
I've tried to export it using exports.module but as I already have router to export, I had a router.use() error.
Here is index.js :
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var indexController = require('../controllers/IndexController');
var booksController = require('../controllers/BooksController');
connection = mysql.createConnection({
debug:true,
host:'localhost',
user:'user',
password:'password',
database:'database'
});
connection.connect(function(error){
if(!!error){
console.log(error);
}else{
console.log('Connected!:)');
}
});
router.get('/', indexController.index);
router.get('/books', booksController.books);
module.exports = router;
Here is booksController.js :
var BooksModel = require('../models/BooksModel');
exports.books = async function(req, res, next){
res.send(await BooksModel.getAllBooks(req, res))
}
Here is booksModel.js :
var connection = require('../routes/index');
async function getAllBooks(req, res){
return await
connection.query("select * from books", function (error,results, fields) {
if (error) throw error;
res.json(results);
});
});
}
module.exports={
getAllBooks
}
I expect to get datas coming from my database, according to the query request. Any help would be really appreciated. Thanks !