Skip to content

findOne({ someField: undefined }) and findOne({ _id: undefined }) do NOT behave like findOne({}) #15551

Closed

Description

@vinayak-88

Prerequisites

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

Mongoose version

8.16.4

Node.js version

20.17.0

MongoDB server version

8.0.11

Typescript version (if applicable)

No response

Description

In the Mongoose docs, it states that:

findOne(undefined) and findOne({ _id: undefined }) are equivalent to findOne({}) and return arbitrary documents.

But this behavior is not consistent anymore.

When I run:

await Model.findOne({ _id: undefined }); await Model.findOne({ someField: undefined });

It returns null instead of returning the first document.

This happens for any field — not just _id — so the doc statement is misleading now.

Steps to Reproduce

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', userSchema);

(async () => {
  try {
    await mongoose.connect('mongodb://localhost:27017/test');

    await User.deleteMany(); // clean slate
    await User.create({ name: 'Vinayak' });

    const res1 = await User.findOne({});                    // Should return document
    const res2 = await User.findOne({ _id: undefined });    // Likely returns null
    const res3 = await User.findOne({ name: undefined });   // Likely returns null

    console.log({ res1, res2, res3 });
  } catch (err) {
    console.error(err);
  } finally {
    await mongoose.disconnect();
  }
})();

Expected Behavior

According to the documentation, both findOne({ _id: undefined }) and findOne({ someField: undefined }) should behave like findOne({}) and return the first document.

But in practice, both return null and only findOne({}) returns a document.

So the documentation should be updated to reflect current Mongoose behavior.

Activity

  1. domharrington commented on Jul 30, 2025

    @domharrington

    This might be related to this change in MongoDB v8: https://www.mongodb.com/docs/manual/release-notes/8.0-compatibility/#queries-for-null-don-t-match-undefined-fields

    You can also use this omitUndefined() helper to strip any undefined query values.

  2. added a commit that references this issue on Aug 4, 2025
    b083270
  3. added this to the 8.17.1 milestone on Aug 4, 2025
  4. added a commit that references this issue on Aug 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions