node.js – knex查询不断要求sqlite模块安装

我正在尝试使用knex创建一个查询,使用postgres作为数据库.但是,当我运行代码时,它一直在询问

Error: Cannot find module ‘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;

最佳答案 我找到了解决方案.我没有正确读取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()
点赞