[英]error on sequelize raw query: query is not a function
I'm trying to use raw queries from sequelize in an express app.我正在尝试在快速应用程序中使用来自 sequelize 的原始查询。 My folder structure is:我的文件夹结构是:
/
/index.js
/models/index.js
/models/price.js
/controllers/price.js
I want to use sequelize which I already define in /models/index.js from a controller.我想使用我已经在 /models/index.js 中从控制器定义的 sequelize。
This is /models/index.js:这是/models/index.js:
"use strict";
var fs = require("fs");
var path = require("path");
var Sequelize = require('sequelize')
, sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {
dialect: "mysql", // or 'sqlite', 'postgres', 'mariadb'
port: 3306, // or 5432 (for postgres)
timezone:'America/Sao_Paulo',
});
sequelize
.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
}, function (err) {
console.log('Unable to connect to the database:', err);
});
var db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
module.exports.db = db;
I want to use a raw query in my price controller:我想在我的价格控制器中使用原始查询:
exports.index = function(req, res, next) {
// var environment_hash = req.session.passport.user.environment_hash;
var Price = require('../models/index').Price;
var db = require('../models/index').db;
console.log(db);
db.query(`SELECT ... `).spread((results, metadata) => {
// Results will be an empty array and metadata will contain the number of affected rows.
console.log(results);
});
var values = {
where: { symbol: 'xxx' },
};
Price
.findOne(values)
.then(function(price) {
console.log("found!!!!!");
console.log(price);
res.render('home/home.ejs', {
price: price
});
});
};
But I'm getting this error message:但我收到此错误消息:
db: [Circular] }
TypeError: db.query is not a function
How can I fix this?我怎样才能解决这个问题?
The Sequelize library is being assigned to a variable on the db object. Sequelize 库被分配给 db 对象上的一个变量。
The error is in the second file instead of calling错误在第二个文件中而不是调用
db.query
We should call我们应该打电话
db.serialize.query
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.在另一种情况下,我们可以将查询函数分配给 db 对象上的一个属性。
db.query = db.serialize.query
or you can de-structure using ES6或者你可以使用 ES6 解构
db.query = { query } = db.serialize
Now we can run db.query
as expected.现在我们可以按预期运行db.query
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.