Skip to content

mongoose.connection.db can be undefined, but TypeScript says it can't #14789

Closed

Description

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

7.6.13, 8.5.2

Node.js version

20.12.2

MongoDB server version

6.0.16

Typescript version (if applicable)

5.5.4

Description

┌─────────────────────────────────────────────────────────────┐
│(property) Connection.db: mongoose.mongo.Db                  │
│                                                             │
│The mongodb.Db instance, set when the connection is opened   │
└─────────────────────────────────────────────────────────────┘

The db field is only set after the connection is opened, but TypeScript thinks it can never be undefined.

Steps to Reproduce

import mongoose from 'mongoose';

let db = mongoose.connection.db;
db = undefined;

It failed to compile:

mongoose-ts.mts:4:1 - error TS2322: Type 'undefined' is not assignable to type 'Db'.

4 db = undefined;
  ~~

It also caused code like this to be flagged by TypeScript ESLint @typescript-eslint/no-unnecessary-condition rule:

if (mongoose.connection.db == null) {

Expected Behavior

It should compile. mongoose.connection.db could be undefined before mongoose.connect was called, so TypeScript should not raise a type error here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    typescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions