-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
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.