Peter Pik Peter Pik - 2 months ago 36
Node.js Question

knex query keep asking for sqlite module install

I'm trying to create a query using knex, by using postgres as database. However when I run the code it keep asking


Error: Cannot find module 'sqlite3'


Even though I have added
pg
to my knexfile.

Query

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;

Answer

I found a solution. i was not reading the knexfile correctly what i did was to create a seperate db.js file with:

var config      = require('../knexfile.js');
var env         = 'development';
var knex        = require('knex')(config[env]);

module.exports = knex;

knex.migrate.latest([config]);

then i used

var db  = require('./db');

then i use knex like

db.knex()