Automattic/mongoose · error · MongooseError

Invalid connection state: ${val}

Error message

Invalid connection state: ${val}

What it means

Error "Invalid connection state: ${val}" thrown in Automattic/mongoose.

Source

Thrown at lib/connection.js:135

Object.defineProperty(Connection.prototype, 'readyState', {
  get: function() {
    // If connection thinks it is connected, but we haven't received a heartbeat in 2 heartbeat intervals,
    // that likely means the connection is stale (potentially due to frozen AWS Lambda container)
    if (
      this._readyState === STATES.connected &&
      this._lastHeartbeatAt != null &&
      // LoadBalanced topology (behind haproxy, including Atlas serverless instances) don't use heartbeats,
      // so we can't use this check in that case.
      this.client?.topology?.s?.description?.type !== 'LoadBalanced' &&
      typeof this.client?.topology?.s?.description?.heartbeatFrequencyMS === 'number' &&
      Date.now() - this._lastHeartbeatAt >= this.client.topology.s.description.heartbeatFrequencyMS * 2) {
      return STATES.disconnected;
    }
    return this._readyState;
  },
  set: function(val) {
    if (!(val in STATES)) {
      throw new MongooseError('Invalid connection state: ' + val);
    }

    if (this._readyState !== val) {
      this._readyState = val;
      // [legacy] loop over the otherDbs on this connection and change their state
      for (const db of this.otherDbs) {
        db.readyState = val;
      }

      if (STATES.connected === val) {
        this._hasOpened = true;
      }

      this.emit(STATES[val]);
    }
  }
});

View on GitHub (pinned to 49cdab0136)

When it happens

Trigger: Thrown at lib/connection.js:135 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of Automattic/mongoose@49cdab0136 (2026-08-21). Data as JSON: /api/errors/cb12872b0a6d6a7c. Report an issue: GitHub.