Mongoose版本错误-这是如何工作的?
我正在试图理解版本错误。每次我认为我对它有了一个坚定的理解,我发现我仍然偏离了底线。有人能帮我理解为什么重新储蓄仍然有效吗Mongoose版本错误-这是如何工作的?,mongoose,Mongoose,我正在试图理解版本错误。每次我认为我对它有了一个坚定的理解,我发现我仍然偏离了底线。有人能帮我理解为什么重新储蓄仍然有效吗 context('when dealing with multiple updates to the same thing', () => { let thing; let thingA; let thingB; before(async () => { thing = utils.generateThing(); await t
context('when dealing with multiple updates to the same thing', () => {
let thing;
let thingA;
let thingB;
before(async () => {
thing = utils.generateThing();
await thing.save();
// Get the thing directly from the database (same thing, different object)
thingA = await models.Thing.findOne({ '_id': thing._id });
thingB = await models.Thing.findOne({ '_id': thing._id });
});
it('should handle the update', async () => {
let yupItSaved = false;
// Save modified thing to database (bumps the version)
thingA.set('propertyArray', ['Monday', 'Tuesday']);
await thingA.save();
// Then try and save thing object
thingB.set('propertyArray', ['Monday', 'Tuesday']);
try {
thingB.__v.should.equal(0);
thingA.__v.should.equal(1);
await thingB.save();
should.fail(null, null, 'VersionError was not thrown');
} catch (err) {
// Expect the VersionError here since versions don't match
err.name.should.equal('VersionError');
const thingAfterError = await models.Thing.findOne({ '_id': thing._id });
thingAfterError.__v.should.equal(1);
thingA.__v.should.equal(1);
thingB.__v.should.equal(0);
// Don't understand why this works even though versions still don't match
await thingB.save();
yupItSaved = true;
}
yupItSaved.should.equal(true);
});
});
mongoose.set(“debug”,true)
并查看发布的查询/更新。无论如何,使用save()
是一种糟糕的模式。您应该始终使用MongoDB的原子更新修饰符,而不是find()
然后“在代码中更改”然后save()
。相信像这样的外部机制注定会失败。我感谢你的评论,我在很短的时间内意识到我一直在使用这种保存不好的代码。但是我不是很适合改变它。真的吗?你认为什么东西这么难改变。问题是,正如俗话所说,你可能是“找错了方向”。解决方案不是“使版本工作”,而是认识到原子修饰符如何使这些事情变得不必要。如果不是完全危险的话,不花时间去理解这些事情。是的,真的。您的回答似乎暗示a)我是从零开始写这段代码的,可以按照我想要的方式来写;或者b)您对我正在使用的应用程序有很好的洞察力,能够说更改是微不足道的。@NeilLunn-mongoose文档似乎促使人们使用save
:“save()函数通常是使用Mongoose更新文档的正确方法。“()。另外,如果存在save中间件,原子更新不会导致执行这些更新,对吗?