mongodb/laravel-mongodb · error · InvalidArgumentException

Database is not properly configured.

Error message

Database is not properly configured.

What it means

The connection needs a database name, resolved either from the 'database' config key or parsed out of the DSN path. If the config has no 'database' and the DSN does not contain a /dbname path segment, Connection::getDefaultDatabaseName() throws InvalidArgumentException.

Solutions

  1. Add a database path to the DSN: 'mongodb://localhost:27017/mydb'
  2. Set the 'database' key in the connection config in config/database.php
  3. Verify the MONGODB_DATABASE env var is not empty if the config reads from env()
  4. Check the DSN for typos — the database must appear after the host before any '?'

Example fix

// before
'dsn' => 'mongodb://localhost:27017?retryWrites=true',
// after
'dsn' => 'mongodb://localhost:27017/myapp?retryWrites=true',
Defensive patterns

Strategy: validation

Validate before calling

$config = config('database.connections.mongodb');
if (empty($config['database']) && !preg_match('/^mongodb(?:\+srv)?:\/\/.+?\/([^?&]+)/s', $config['dsn'] ?? '', $m)) {
    throw new RuntimeException('Set database key or add /dbname to the DSN');
}

Type guard

function hasResolvableDatabase(array $config): bool {
    return !empty($config['database'])
        || (is_string($config['dsn'] ?? null) && preg_match('/^mongodb(?:\+srv)?:\/\/.+?\/([^?&]+)/s', $config['dsn'], $m) === 1);
}

Try / catch

try {
    DB::connection('mongodb')->table('users')->get();
} catch (InvalidArgumentException $e) {
    if (str_contains($e->getMessage(), 'not properly configured')) {
        config(['database.connections.mongodb.database' => env('MONGODB_DATABASE', 'default_db')]);
    } else {
        throw $e;
    }
}

Prevention

When it happens

Trigger: Creating a MongoDB connection (db connection in config/database.php) where 'database' is empty/null and the 'dsn' has no database in its path, e.g. 'mongodb://localhost:27017' with no trailing '/mydb'.

Common situations: Config copied from examples that authenticate via DSN options but omit the db path; empty env var (MONGODB_DATABASE='') silently producing an empty database config; switching from host/port config to DSN without adding the db segment.

Understand the failure class

Background: "is required", "must be set", "missing required field": configuration validation errors across open-source libraries — this error's family across 36 libraries.

Related errors


AI-assisted analysis of mongodb/laravel-mongodb@0634653039 (2026-09-15). Data as JSON: /api/errors/9823e762b4362c05. Report an issue: GitHub.

Appendix: source

Thrown at src/Connection.php:225

            // The parent method enable query log using enableQueryLog()
            // but disables it by setting $loggingQueries to false. We need to
            // remove the subscriber for performance.
            if (! $this->loggingQueries) {
                $this->disableQueryLog();
            }
        }
    }

    /**
     * Get the name of the default database based on db config or try to detect it from dsn.
     *
     * @throws InvalidArgumentException
     */
    protected function getDefaultDatabaseName(string $dsn, array $config): string
    {
        if (empty($config['database'])) {
            if (! preg_match('/^mongodb(?:[+]srv)?:\\/\\/.+?\\/([^?&]+)/s', $dsn, $matches)) {
                throw new InvalidArgumentException('Database is not properly configured.');
            }

            $config['database'] = $matches[1];
        }

        return $config['database'];
    }

    /**
     * Create a new MongoDB connection.
     */
    protected function createConnection(string $dsn, array $config, array $options): Client
    {
        // By default driver options is an empty array.
        $driverOptions = [];

        if (isset($config['driver_options']) && is_array($config['driver_options'])) {
            $driverOptions = $config['driver_options'];

View on GitHub (pinned to 0634653039)