2017-12-07 8 views
1

명시 적 응용 프로그램에서 후속 작업에서 원시 쿼리를 사용하려고합니다. 내 폴더 구조는 다음과 같습니다 나는 이미 컨트롤러에서 /models/index.js에 정의 sequelize를 사용하려면원시 쿼리를 sequelize 할 때 오류가 발생했습니다 : 쿼리가 함수가 아닙니다.

/ 
/index.js 
/models/index.js 
/models/price.js 
/controllers/price.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 

어떻게 해결할 수 있습니까?

+0

호출 쿼리를 함수로 ... 'SELECT ...'문자열을 전달하면 db가 제대로 가져 오지 않았거나 'query'속성이 첨부되지 않은 것처럼 보입니다. –

+0

index.js에서 db 객체에 쿼리 함수가 필요합니다 ... 그렇지 않으면 무엇을 호출하고 있습니까? 쿼리가 후속 기능에서 나온다면 아마도 db.sequelize.query라고 말할 것입니다. –

+0

'models/index' 파일이'db'라는 함수를 내보내는 것을 수정하면 문제를 해결할 수 있습니다. 'module.exports.db = function() {...}' –

답변

2

Sequelize 라이브러리가 db 오브젝트의 변수에 지정됩니다.

오류는 우리는 우리가 존재하지 않는 함수를 호출 한 첫 번째 경우

db.serialize.query 

를 호출해야 두 번째 파일 대신

db.query 

를 호출입니다. 다른 경우에는 쿼리 함수를 db 객체의 속성에 할당 할 수 있습니다.

db.query = serialize.query 

이제 우리는 예상대로 db.query을 실행할 수 있습니다.