javascript - error on sequelize raw query: query is not a function - Stack Overflow

I'm trying to use raw queries from sequelize in an express app.My folder structure is:index.js

I'm trying to use raw queries from sequelize in an express app. 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.

This is /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?

I'm trying to use raw queries from sequelize in an express app. 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.

This is /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?

Share Improve this question asked Dec 7, 2017 at 1:53 Filipe FerminianoFilipe Ferminiano 8,81127 gold badges113 silver badges180 bronze badges 7
  • Your calling query as a function... and passing in a string SELECT ... it looks like db isn't being imported correctly or doesn't have the property 'query' attached. – Daniel Tate Commented Dec 7, 2017 at 1:56
  • In your index.js your db object needs a query function... otherwise what are you calling? If query is a function from sequelize then maybe you mean to say db.sequelize.query – Daniel Tate Commented Dec 7, 2017 at 1:57
  • You can fix it by making sure your models/index file is exporting a function named db. module.exports.db = function () {...} – Ryan Wheale Commented Dec 7, 2017 at 1:57
  • I'm using sequelize lib which contains the query function: docs.sequelizejs./manual/tutorial/raw-queries.html – Filipe Ferminiano Commented Dec 7, 2017 at 1:58
  • use db.sequelize.query instead of db.query If you look at your current code your attaching the library to the property sequelize not assigning it. – Daniel Tate Commented Dec 7, 2017 at 1:59
 |  Show 2 more ments

1 Answer 1

Reset to default 4

The Sequelize library is being assigned to a variable on the db object.

The error is in the second file instead of calling

db.query

We should call

db.sequelize.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.query = db.sequelize.query

or you can de-structure using ES6

db.query = { query } = db.sequelize

Now we can run db.query as expected.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745255166a4618909.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信