Skip to content
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

Make create() wait for all documents to finish inserting or error out before throwing an error if ordered = false #4628

Closed
enrichz opened this issue Oct 14, 2016 · 2 comments

Comments

@enrichz
Copy link

enrichz commented Oct 14, 2016

Hello,
I'm facing a very weird problem which unfortunately happens randomly, so I can put the code that actually reproduces it.

Ideally is something like this:
The model

var aSchema = new Schema({
  _id: {
    type: String
  }
});
mongoose.model("A", aSchema);

The operations:

var mongoose = require("mongoose");
var A = mongoose.model("A");
  A.create([{_id: "a"}, {_id: "b"}, {_id: "a"}], function(err, result){
    A.remove({_id: {$in: ["a", "b"]}}, function(err, result) {
      console.log(result);
    });
  });

So the problem is that sometimes, the elements do not get removed, without any error being thrown.
It is interesting to note that if i put a setTimeout (2 seconds is enough) between the create and the remove, the elements get removed.

Also, it looks like that if the create doesn't throw an error, the problem never occurs. This is the reason why I put a duplicate _id in the elements.

Any idea? I'm using mongoose 4.5.5

Thanks

@vkarpov15
Copy link
Collaborator

You've got a pretty subtle race condition there: create() just does a bunch of save() calls in parallel and fails when the first insert fails. However, it does not cancel the other save() calls, so more docs can be inserted after the create() callback happens. If you need to ensure that all docs were either inserted or failed to insert, I'd recommend you use insertMany() instead of create(). We'll improve this for the next backwards breaking release though.

@vkarpov15 vkarpov15 added this to the 5.0 milestone Oct 22, 2016
@enrichz
Copy link
Author

enrichz commented Oct 24, 2016

It works fine this way thank you. Also it seems faster :)

@vkarpov15 vkarpov15 modified the milestones: Parking Lot, 8.0 Jun 21, 2023
@vkarpov15 vkarpov15 changed the title Model.remove({_id: {$in: ids}}) does not remove Make create() wait for all documents to finish inserting or error out before throwing an error if ordered = false Jun 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants