hsliuping/TradingAgents-CN · critical · ValueError

MongoDB连接字符串未配置。请通过以下方式之一进行配置:\n1. 设置环境变量 MONGODB_CONNECTION

Error message

MongoDB连接字符串未配置。请通过以下方式之一进行配置:\n1. 设置环境变量 MONGODB_CONNECTION_STRING\n2. 在初始化时传入 connection_string 参数\n例如: MONGODB_CONNECTION_STRING=mongodb://localhost:27017/

What it means

Raised by MongoDBStorage.__init__ when neither the connection_string argument nor the MONGODB_CONNECTION_STRING environment variable provides a value. This intentionally removed the old hardcoded localhost default.

Source

Thrown at tradingagents/config/mongodb_storage.py:38

    from pymongo import MongoClient
    from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError
    MONGODB_AVAILABLE = True
except ImportError:
    MONGODB_AVAILABLE = False
    MongoClient = None


class MongoDBStorage:
    """MongoDB存储适配器"""
    
    def __init__(self, connection_string: str = None, database_name: str = "tradingagents"):
        if not MONGODB_AVAILABLE:
            raise ImportError("pymongo is not installed. Please install it with: pip install pymongo")
        
        # 修复硬编码问题 - 如果没有提供连接字符串且环境变量也未设置,则抛出错误
        self.connection_string = connection_string or os.getenv("MONGODB_CONNECTION_STRING")
        if not self.connection_string:
            raise ValueError(
                "MongoDB连接字符串未配置。请通过以下方式之一进行配置:\n"
                "1. 设置环境变量 MONGODB_CONNECTION_STRING\n"
                "2. 在初始化时传入 connection_string 参数\n"
                "例如: MONGODB_CONNECTION_STRING=mongodb://localhost:27017/"
            )
        
        self.database_name = database_name
        self.collection_name = "token_usage"
        
        self.client = None
        self.db = None
        self.collection = None
        self._connected = False
        
        # 尝试连接
        self._connect()
    
    def _connect(self):

View on GitHub (pinned to 74783e8817)

Solutions

  1. export MONGODB_CONNECTION_STRING=mongodb://localhost:27017/
  2. Or pass it explicitly: MongoDBStorage(connection_string='mongodb://localhost:27017/')
  3. Check for typos/whitespace in the env var name and value

Example fix

# before
storage = MongoDBStorage()
# after
storage = MongoDBStorage(connection_string=os.environ['MONGODB_CONNECTION_STRING'])
Defensive patterns

Strategy: validation

Validate before calling

import os
cs = os.getenv('MONGODB_CONNECTION_STRING')
if not cs:
    raise SystemExit('MONGODB_CONNECTION_STRING not set; refusing to start')
storage = MongoDBStorage(connection_string=cs)

Try / catch

try:
    storage = MongoDBStorage()
except ValueError as e:
    if 'MongoDB' in str(e):
        storage = MongoDBStorage(connection_string='mongodb://localhost:27017/')

Prevention

When it happens

Trigger: new MongoDBStorage() with no arguments and no MONGODB_CONNECTION_STRING in the environment; or passing connection_string=None explicitly while env var is unset.

Common situations: Upgrading to a version that removed the hardcoded default, running scripts outside docker-compose where the env var was injected, or passing the connection string under a different variable name.

Understand the failure class

Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.

Related errors


AI-assisted analysis of hsliuping/TradingAgents-CN@74783e8817 (2026-08-28). Data as JSON: /api/errors/2e4394adf597ae49. Report an issue: GitHub.