我已经阅读了人们在使用版本 key 时遇到的其他问题/答案,但由于某种原因,我不明白为什么在我的情况下会发生这种情况。
所以我有以下 Mocha 测试:
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);
});
});
});
一切都很好并且通过了。即使在运行时我也没有遇到任何其他问题。
现在,当我尝试在第一个测试之后再次运行相同的测试时,即:
it('should be able to save one job', function (done) {
.....
});
it('should be able to save one job again', function (done) {
.....
});
第二个失败并出现错误:
VersionError: No matching document found.
我真的不明白为什么会发生这种情况,因为我已经第一次推送到数组,没有版本控制问题。为什么连续第二次失败?
最佳答案
Mongoose versionKey在文档中保存版本号,通常命名为__v
。
只要对数组的修改可能会更改任何数组的元素位置,该值就会自动递增。对于需要使用位置表示法的任何更新,该值也会在 where 子句中一起发送。如果我们的 where 子句仍然与文档匹配,则可以确保没有其他操作更改了我们的数组元素位置,并且可以使用位置语法。 (read more here)
在您的测试中,在第一次 save()
之后,文档有一个递增的 __v
,应该在您的文档上更新它,以供 Mongoose 使用作为第二个 save()
上的 where 子句
。
关于node.js - 版本错误: No matching document found error only on (Mocha) test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26554487/