Make `create()` wait for all documents to finish inserting or error out before throwing an error if `ordered = false`
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
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.
It works fine this way thank you. Also it seems faster :)