findOneAndUpdate method - produces inappropriate results on missing to pass first argument #14913
Open
2 tasks done
Labels
enhancement
This issue is a user-facing general improvement that doesn't fix a bug or add a new feature
Milestone
Prerequisites
Mongoose version
8.6.3
Node.js version
20.16.0
MongoDB server version
6.8.0
Typescript version (if applicable)
No response
Description
Description:
I encountered unexpected behaviour when using the findOneAndUpdate() method. When I omitted the first argument (the filter object), which typically should contain a unique identifier like _id to identify the document to update, Mongoose did not throw an error as expected.
Current behaviour:
Instead of throwing an error, Mongoose selects and updates the first document in the collection. This behaviour can lead to unintended data modifications, especially in large-scale or data-sensitive applications where precise updates are crucial.
Specifically, it appears that when an empty filter object {} is provided (or implicitly when the filter argument is omitted), Mongoose defaults to updating the first document it finds, potentially based on the natural order of documents in the collection (which often correlates with creation time, but this isn't guaranteed).
Proposed solution:
This change would help prevent accidental updates to unintended documents and align with the principle of least astonishment, especially for developers new to Mongoose or MongoDB.
Additional context:
This behaviour is particularly concerning in applications where data integrity is paramount. It could lead to silent errors where developers believe they're updating a specific document, but are actually modifying an arbitrary one.
Version information:
[Mongoose -"version": "8.6.3" and MongoDB - "version": "6.8.0", nodejs - version - 20.16.0]
Thank you for considering this issue. I believe addressing it would significantly improve Mongoose's safety and predictability.
Steps to Reproduce
To reproduce the error:
1.Make sure you have MongoDB running locally on the default port (27017).
2.Save the above code in a file named reproduce_error.js.
3.Run the script using Node.js:
4.Observe the output. You should see that one of the users (likely the first one added) has been updated without specifying any filter.
Expected Behavior
Expected behaviour:
Mongoose should throw an error or return null when no filter is provided, prompting the developer to supply a unique identifier to target a specific document for update.
The text was updated successfully, but these errors were encountered: