如何为Knex设置默认数据库?knexfile.js正确配置方式咨询
Got it, let's sort out this default database configuration issue for you. The default: true flag you tried doesn't work because Knex doesn't recognize that property in the knexfile structure—each top-level key in the exported object is treated as an environment name (like development, production), and Knex uses the NODE_ENV environment variable to pick which one to use (falling back to development if NODE_ENV isn't set).
Here are the most common and correct ways to set your desired default database:
1. Rename your target environment to development (simplest default)
Knex automatically loads the development configuration if no environment is specified. Just rename your local key to development, and you're good to go:
module.exports = { development: { client: 'postgresql', connection: { database: 'main' }, pool: { min: 2, max: 10 } }, // Add other environments like production/staging here if needed };
Then initialize Knex without extra parameters—it will use the development config by default:
const knex = require('knex')(require('./knexfile'));
2. Keep your local environment and explicitly set it as default
If you want to keep the local name, you have two options:
Option A: Specify the environment directly when initializing Knex
Just reference the local config explicitly when creating your Knex instance:
const knexConfig = require('./knexfile'); const knex = require('knex')(knexConfig.local);
Option B: Fall back to local if NODE_ENV isn't set
You can modify your initialization code to use local as the default when no environment variable is provided:
const env = process.env.NODE_ENV || 'local'; const knexConfig = require('./knexfile')[env]; const knex = require('knex')(knexConfig);
This way, if you run your app with NODE_ENV=production node app.js, it will use the production config; otherwise, it defaults to local.
3. Share the default config across multiple environments
If you want local to be the base for other environments, you can define it once and reuse it:
const defaultConfig = { client: 'postgresql', connection: { database: 'main' }, pool: { min: 2, max: 10 } }; module.exports = { local: defaultConfig, development: defaultConfig, // Makes development use the same default settings production: { ...defaultConfig, connection: { database: 'main_prod', // Add production-specific connection details like user/password here } } };
That's all—pick the method that fits your workflow best!
内容的提问来源于stack exchange,提问作者Allyl Isocyanate

