sequelize原始查询的错误:查询不是函数

时间:2017-12-07 01:53:53

标签: javascript node.js express sequelize.js

我正在尝试使用快速应用程序中的sequelize原始查询。 我的文件夹结构是:

/
/index.js
/models/index.js
/models/price.js
/controllers/price.js

我想使用sequelize,我已经在控制器的/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;

我想在价格控制器中使用原始查询:

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
                });
      });
};

但我收到此错误消息:

db: [Circular] }
TypeError: db.query is not a function

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

Sequelize库被分配给db对象上的变量。

错误发生在第二个文件中,而不是调用

db.query

我们应该致电

db.serialize.query

在第一种情况下,我们调用了一个不存在的函数。在另一种情况下,我们可以将查询函数分配给db对象上的属性。

db.query = serialize.query

现在我们可以按预期运行db.query