-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
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
Use findOneAndUpdate for save? #5488
Comments
i think i know what you mean, but can you post a repro script so I know exactly what you're talking about? Sometimes |
The save routine in mongoose.js doesn't validate the data being returned from MongoDB, so if the developer forgets to use markModified on a date or Mixed Type, the return result incorrectly indicates the data was saved to the database. ExampleModel async function test() {
let example = new ExampleModel();
await example.save();
example = await ExampleModel.findOne().exec();
// Note no markModified used
example.myDate.setMonth(example.myDate.getMonth() + 1);
// Returns example with myDate one month in the future
example = await example.save();
// Returns example with myDate on the current month
example = await ExampleModel.findOne().exec();
} |
this has always been a problem. I don't know if the @vkarpov15 what do you think is the best way to handle this edge case? |
We've thought about switching to findOneAndUpdate for save rather than just update, but that adds a lot of performance overhead because findOneAndUpdate is slower and because we would have to hydrate a new mongoose doc after every save. Worth investigating more. Re: your concerns with setMonth, that's question 4 on the faq. http://mongoosejs.com/docs/faq.html |
This is a bug in how the save function operates.
The save function assumes that all values are properly updated and returns the same object passed to save (with minor changes such as version update).
Any updated to the object that mongoose doesn't recognize will be affected. For example if you update a date with setMonth (without using markModified), mongoose.js will not recognize it and will claim the object was properly updated on save, when it fact it wasn't.
The desired outcome should be an error returned if the return value from the database does not match the saved object. If returning an error doesn't work, then the returned object should be the one from the database, not the one that was passed to the save function.
Currently using Node v8.0.0, Mongoose v4.10.5, and MongoDB v3.4.1.
The text was updated successfully, but these errors were encountered: