本文介绍了与knex的未定义的数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行以下脚本node acl.js:

acl.js

require('dotenv').config()

const _ = require('lodash');
const buckets = require('./buckets');
const knex = require('../src/config/db'); //HERE I am getting the ERROR

var downSql = 'DROP TABLE IF EXISTS "{{prefix}}{{meta}}";'+
    'DROP TABLE IF EXISTS "{{prefix}}{{resources}}";'+
    'DROP TABLE IF EXISTS "{{prefix}}{{parents}}";'+
    'DROP TABLE IF EXISTS "{{prefix}}{{users}}";'+
    'DROP TABLE IF EXISTS "{{prefix}}{{roles}}";'+
    'DROP TABLE IF EXISTS "{{prefix}}{{permissions}}";';
var upSql = 'CREATE TABLE "{{prefix}}{{meta}}" (key TEXT NOT NULL PRIMARY KEY, value TEXT[][] NOT NULL);'+
    'INSERT INTO "{{prefix}}{{meta}}" VALUES (\'users\', \'{}\');'+
    'INSERT INTO "{{prefix}}{{meta}}" VALUES (\'roles\', \'{}\');'+
    'CREATE TABLE "{{prefix}}{{resources}}" (key TEXT NOT NULL PRIMARY KEY, value TEXT[][] NOT NULL);'+
    'CREATE TABLE "{{prefix}}{{parents}}" (key TEXT NOT NULL PRIMARY KEY, value TEXT[][] NOT NULL);'+
    'CREATE TABLE "{{prefix}}{{roles}}" (key TEXT NOT NULL PRIMARY KEY, value TEXT[][] NOT NULL);'+
    'CREATE TABLE "{{prefix}}{{users}}" (key TEXT NOT NULL PRIMARY KEY, value TEXT[][] NOT NULL);'+
    'CREATE TABLE "{{prefix}}{{permissions}}" (key TEXT NOT NULL PRIMARY KEY, value JSON NOT NULL);';

function tmpl(str, ctx) {
    var n = 1;
    var sql = str.replace(/{{(\w+)}}/g, function(match, cap1) {
        return ctx[cap1] || match;
    });
    return sql.replace(/\?/g, function() { return '$' + n++; });
}

function createTables(callback) {
    var prefix = ''
    var bucketNames = buckets(args[8])

    if (!prefix) prefix = 'acl_';

    knex.raw(tmpl(downSql+upSql, {
            'meta': bucketNames.meta,
            'parents': bucketNames.parents,
            'permissions': bucketNames.permissions,
            'prefix': prefix,
            'resources': bucketNames.resources,
            'roles': bucketNames.roles,
            'users': bucketNames.users
        }))
        .then(function() {
            if (!_.isUndefined(callback)) {
                callback(null, db);
            }
        })
    ;
}

createTables()

buckets.js

'use strict';

var _ = require('lodash');

var buckets = function(options){
    return _.extend({
        meta: 'meta',
        parents: 'parents',
        permissions: 'permissions',
        resources: 'resources',
        roles: 'roles',
        users: 'users'
    }, options);
};

exports = module.exports = buckets;

当我运行node acl.js时,出现以下错误:

When I run node acl.js I get the following error:

> node acl.js
{ development:
   { client: undefined,
     connection: { user: undefined, password: undefined, database: undefined } } }
undefined
C:\Users\admin\Desktop\Coding Projects\learning_npm_node_acl\node_modules\knex\lib\index.js:49
  if (arguments.length === 0 || !config.client && !config.dialect) {
                                       ^

TypeError: Cannot read property 'client' of undefined
    at Knex (C:\Users\admin\Desktop\Coding Projects\learning_npm_node_acl\node_modules\knex\lib\index.js:49:40)
    at Object.<anonymous> (C:\Users\admin\Desktop\Coding Projects\learning_npm_node_acl\src\config\db.js:8:29)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Module.require (module.js:517:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Users\admin\Desktop\Coding Projects\learning_npm_node_acl\node_acl\acl.js:5:14)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Function.Module.runMain (module.js:609:10)

错误来自我的acl.js文件中的行const knex = require('../src/config/db');.

The error comes from the line const knex = require('../src/config/db'); in my acl.js file.

我的db.js文件如下所示:

require('dotenv').config()
// Loading from an external file
const config = require('../../knexfile')
console.log(config)
const env = process.env.DB_ENV
console.log(env)

const knex = require('knex')(config[env])

knex.on('query', (queryData) => {
  console.log(queryData)
})

module.exports = knex

如您所见,在上面显示的输出中,console.log语句大部分返回了undefined.

As you can see the console.log statements give back mostly undefined in the above shown output.

knexfile.js正在从.env file

knexfile.js

require("dotenv").config()

module.exports = {

    development: {
        client: process.env.DB_CONNECTION,
        connection: {
            user: process.env.DB_USERNAME,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_DATABASE,
        },
    },
}

.env

# Database
DB_CONNECTION=postgresql
DB_ENV=development
DB_USERNAME=root
DB_PASSWORD=root
DB_DATABASE=nodeacl

当我运行knex migrate:latestknex seed:run时,种子和迁移文件运行完美.

When I run knex migrate:latest or knex seed:run the seeds and migration files run perfectly.

任何建议为何会出现上述错误?

Any suggestions why I am getting the above shown error?

推荐答案

当您运行knex migrate:latestknex seed:run时,它可以工作,因为文件knexfile.js与文件.env位于同一级别.文件系统.这意味着您的环境变量已正确导入.

When you run knex migrate:latest and knex seed:run, it works because your file knexfile.js is located at the same level as your file .env in your file system. That means your environment variables is correctly imported.

您的文件acl.js是否处于同一级别?如果没有,也许您应该从.env级别运行node /path/to/acl.js.

Is your file acl.js at the same level ? If not, maybe you should run node /path/to/acl.jsfrom the .env level.

这篇关于与knex的未定义的数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 04:21