Express API model MVC - Error : connection.query is not a function

590 views
Skip to first unread message

weird ow.

unread,
Jun 27, 2019, 4:50:19 PM6/27/19
to nodejs

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 !

Chaiwa Berian

unread,
Jun 28, 2019, 12:15:01 AM6/28/19
to nodejs
In index.js you are not exporting the connection object, you are only exporting router object. That is why you are getting the error when you reference connection object in booksModel.js. You could try the following:
Step 1: In index.js include connection in the module exports as below:
module.exports={
router,
connection
}
Step 2: To reference it in booksModel.js, do below:
const connection = require('../routes/index').connection;

Step 3: Use connection to query your db.

Let me know how it goes.

weird ow.

unread,
Jun 28, 2019, 12:49:32 PM6/28/19
to nodejs
Thanks for your answer! So I followed the steps and I got this error : TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object

It comes from the module.exports which doesn't like multiples variables.

I forgot to say I also tried this : exports.connection = mysql.createConnection() but it doesn't work either..
Reply all
Reply to author
Forward
0 new messages