I’m trying to use raw queries from sequelize in an express app. My folder structure is:
JavaScript
x
6
1
/
2
/index.js
3
/models/index.js
4
/models/price.js
5
/controllers/price.js
6
I want to use sequelize which I already define in /models/index.js from a controller.
This is /models/index.js:
JavaScript
1
47
47
1
"use strict";
2
3
var fs = require("fs");
4
var path = require("path");
5
var Sequelize = require('sequelize')
6
, sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {
7
dialect: "mysql", // or 'sqlite', 'postgres', 'mariadb'
8
port: 3306, // or 5432 (for postgres)
9
timezone:'America/Sao_Paulo',
10
});
11
12
13
sequelize
14
.authenticate()
15
.then(function(err) {
16
console.log('Connection has been established successfully.');
17
}, function (err) {
18
console.log('Unable to connect to the database:', err);
19
});
20
21
22
23
var db = {};
24
fs
25
.readdirSync(__dirname)
26
.filter(function(file) {
27
return (file.indexOf(".") !== 0) && (file !== "index.js");
28
})
29
.forEach(function(file) {
30
var model = sequelize.import(path.join(__dirname, file));
31
db[model.name] = model;
32
});
33
34
Object.keys(db).forEach(function(modelName) {
35
if ("associate" in db[modelName]) {
36
db[modelName].associate(db);
37
}
38
});
39
40
db.sequelize = sequelize;
41
db.Sequelize = Sequelize;
42
43
44
45
module.exports = db;
46
module.exports.db = db;
47
I want to use a raw query in my price controller:
JavaScript
1
30
30
1
exports.index = function(req, res, next) {
2
3
// var environment_hash = req.session.passport.user.environment_hash;
4
5
var Price = require('../models/index').Price;
6
var db = require('../models/index').db;
7
8
console.log(db);
9
10
db.query(`SELECT ... `).spread((results, metadata) => {
11
// Results will be an empty array and metadata will contain the number of affected rows.
12
console.log(results);
13
});
14
15
16
var values = {
17
where: { symbol: 'xxx' },
18
};
19
20
Price
21
.findOne(values)
22
.then(function(price) {
23
console.log("found!!!!!");
24
console.log(price);
25
res.render('home/home.ejs', {
26
price: price
27
});
28
});
29
};
30
But I’m getting this error message:
JavaScript
1
3
1
db: [Circular] }
2
TypeError: db.query is not a function
3
How can I fix this?
Advertisement
Answer
The Sequelize library is being assigned to a variable on the db object.
The error is in the second file instead of calling
JavaScript
1
2
1
db.query
2
We should call
JavaScript
1
2
1
db.sequelize.query
2
In the first case we have called a function that does not exist. In another case we could assign the query function to a property on the db object.
JavaScript
1
2
1
db.query = db.sequelize.query
2
or you can de-structure using ES6
JavaScript
1
2
1
db.query = { query } = db.sequelize
2
Now we can run db.query
as expected.