-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
findByIdAndUpdate should not work with undefined id #10964
Comments
When you call |
Hi @IslandRhythms, I understand that, I am just saying that it is an unexpected behavior, which in my case made a bug much harder to track and to understand than if the id parameter was mandatory (with control checking). I am not saying that there is a bug, I am suggesting an improvement for the API. |
So something that should be mentioned in the docs? |
Yes, and also a minor change in the code:
|
We took a closer look, and realistically I don't think we should make this particular change. We would have to throw an error in If you need Mongoose to throw an error if filtering by an undefined id, you can use middleware as follows: schema.pre(/.*/, { query: true }, function() {
if (this.getFilter() && this.getFilter()._id === undefined) {
throw new Error('Cannot filter by _id === undefined');
}
}); Below is a working example: 'use strict';
const mongoose = require('mongoose');
const schema = mongoose.Schema({ name: String });
schema.pre(/.*/, { query: true }, function() {
if (this.getFilter() && this.getFilter()._id === undefined) {
throw new Error('Cannot filter by _id === undefined');
}
});
run().catch(err => console.log(err));
async function run() {
await mongoose.connect('mongodb://127.0.0.1/gh10964');
const Test = mongoose.model('Test', schema);
// Throws "Error: Cannot filter by _id === undefined"
await Test.findByIdAndUpdate(undefined, { name: 'foo' });
console.log('Done');
} |
Do you want to request a feature or report a bug?
Neither a feature or a bug, but an improvement for the API
What is the current behavior?
Actually, findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...), as stated by the documentation.
That's working accordingly, however this is not the logically expected behavior when the id is undefined:
findOneAndUpdate({ _id: undefined }, ...)
=> this form, understandably, should update the first entry.findByIdAndUpdate(undefined, ...)
=> this form however should fail.What is the expected behavior?
I expect an argument error when using
findByIdAndUpdate
with an undefined id.What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
Mongoose v5.13.8
The text was updated successfully, but these errors were encountered: