我尝试使用knex创建查询,使用postgres作为数据库。但是,当我运行代码时,它一直在询问
错误:无法找到模块' sqlite3'
即使我已将pg
添加到我的knexfile中。
查询
var data = {
id: leagueId,
slug: leagueSlug,
createdAt: new Date()
};
var query = knex('league').insert(data).toString();
query += ' on duplicate key update ' + knex.raw('createdAt= ?, id = ?',[new Date(), id]);
knex.raw(query);
knexfile
module.exports = {
development: {
client: 'pg',
connection: {
user: 'test',
database: 'test'
}
},
production: {
client: 'pg',
connection: process.env.DATABASE_URL
}
};
index.js
var express = require('express');
var request = require('request');
var parse = require('body-parser');
var knex = require('knex');
var Log = require('log');
var router = express.Router();
var log = new Log('info');
/* Retrieve and save leagues*/
router.get('/api/league', function(req, res, next) {
/* exclude slugs */
var excludedSlugs = [ 'eu-cs', 'na-cs', 'iwc', 'all-star'];
request({
method: 'GET',
uri: 'http://test',
headers: {
'Content-Type': 'application/json',
'dataType': 'json'}
}, function (error, response, body){
if(!error && response.statusCode == 200){
var bodyJSON = JSON.parse(body);
var leagueObjects = bodyJSON["leagues"];
for(var objIndex in leagueObjects){
if (excludedSlugs.indexOf(leagueObjects[objIndex]["slug"]) > -1) {
/* excluded slugs - do nothing */
} else {
var leagueId = leagueObjects[objIndex]["id"];
var leagueSlug = leagueObjects[objIndex]["slug"];
var data = {
id: leagueId,
slug: leagueSlug,
name: "lol",
createdAt: new Date()
};
var query = knex('league').insert(data).toString();
query += ' on duplicate key update ' + 'createdAt= ?, id = ?',[new Date(), leagueId];
knex.raw(query);
}
}
res.json(leagueObjects);
} else {
log.error(error);
}
})
});
module.exports = router;
答案 0 :(得分:2)
我找到了解决方案。我没有正确读取knexfile我所做的是创建一个单独的db.js文件:
var config = require('../knexfile.js');
var env = 'development';
var knex = require('knex')(config[env]);
module.exports = knex;
knex.migrate.latest([config]);
然后我用
var db = require('./db');
然后我使用knex像
db.knex()