ParallelSaveError: Can't save() the same doc multiple times in parallel
See original GitHub issueDo you want to request a feature or report a bug? feature
What is the current behavior? When saving the same model instance from multiple different contexts (multiple different parts of application) setting different values to this model instance before calling save, mongoose produces ParallelSaveError.
I’m writing rather complicated logic in my application that is based of working with mongoose models and using the save() method. Recently I found out that even if mongoose produces ParallelSaveError when trying to save same model in parallel, only the last updated value is saved aftermath (as if the ParallelSaveError errors are ignored).
If you run this sample code, the values setted to the model from the last call of saveNew function ( // step 5 ) will be stored to DB taking precedence to previous steps:
mongoose.connect(
"mongodb://localhost:27017/test",
{ useNewUrlParser: true }
);
const Schema = mongoose.Schema;
const exampleSchema = new Schema({
keyA: Number,
keyB: Number
});
const exampleModel = mongoose.model("example", exampleSchema);
const newDocument = exampleModel({ keyA: 1, keyB: 2 });
newDocument.save().then(() => {
saveNew({ doc: newDocument, keyA: 4, keyB: 0 }); // step 1
saveNew({ doc: newDocument, keyA: 6, keyB: 8 }); // step 2
saveNew({ doc: newDocument, keyA: 9, keyB: 0 }); // step 3
saveNew({ doc: newDocument, keyA: 7, keyB: 3 }); // step 4
saveNew({ doc: newDocument, keyA: 6, keyB: 0 }); // step 5
async function saveNew({ doc, keyA, keyB }) {
try {
if (keyA) {
doc.keyA = keyA;
}
if (keyB) {
doc.keyB = keyB;
}
await doc.save();
console.log("end of saveNew for", keyA, keyB, doc.keyA, doc.keyB);
// end of saveNew for 4 0 6 3 gets logged
} catch (err) {
if (err.name === "ParallelSaveError") {
console.log("There was a parallel save error for", keyA, keyB);
}
}
}
});
So even though only the first step gets resolved ok and the others fall into catch, values from the last step are retained in the model instance and in the DB.
What is the expected behavior?
For me that IS the desired behaviour but I wonder if it is correct. Why the error warnings if the last updated value gets written to database as you would expect? Is there some kind of queue mechanism in mongoose to retain all model values before separate .save() calls?
Can someone please clear some confusion on this topic?
What are the versions of Node.js, Mongoose and MongoDB you are using? Note that “latest” is not a version.
Mongoose: ^5.6.12 Node.js: v8.9.0 MongoDB: pre v4
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:13 (1 by maintainers)
Had the same problem and solved it by using
.findOneAndUpdate()
instead of.save()
Even I am facing this issue. I have to make changes to 2 documents and make a new one in a singe function. Used .save() and .findOneAndUpdate() for first two and now I am unable to create+save a new entry in the end.