mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

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

Open enrichz opened this issue 10 years ago • 2 comments

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

enrichz avatar Oct 14 '16 13:10 enrichz

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 avatar Oct 22 '16 00:10 vkarpov15

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

enrichz avatar Oct 24 '16 07:10 enrichz