Reputation: 2155
I have read the other problems/answers people are having with the version key but for some reason I do not understand why this specifically happens in my case.
So I have the following mocha test:
it('should be able to save one job', function (done) {
Promise.join(user.saveAsync(), company.saveAsync(),
function (savedUser, savedCompany) {
user = savedUser[0];
user.jobs.push(job);
user.saveAsync()
.spread(function (savedUserWithJob) {
user = savedUserWithJob;
user.jobs.should.have.length(1);
done();
})
.catch(function (err) {
done(err);
});
});
});
which is all fine and passes. I did not have any other problems even at runtime.
Now when I try to run the same test again right after the first one i.e.:
it('should be able to save one job', function (done) {
.....
});
it('should be able to save one job again', function (done) {
.....
});
The second one fails with the error:
VersionError: No matching document found.
I really do not understand why that happens as I am already pushing to the array the first time with no versioning problems. Why is it failing the second consecutive time?
Upvotes: 2
Views: 251
Reputation: 1306
Mongoose versionKey saves an version number on document, usually named __v
.
This value is atomically incremented whenever a modification to an array potentially changes any array’s elements position. This value is also sent along in the where clause for any updates that require the use of positional notation. If our where clause still matches the document, it ensures that no other operations have changed our array elements position and it is ok to use use positional syntax. (read more here)
In your tests, after first save()
, the doc has an incremented __v
, that should be updated on your doc to be used by mongoose as part of the where clause
on second save()
.
Upvotes: 1