Mongoose 版本错误 - 这是如何工作的?

问题描述 投票:0回答:1

我正在尝试理解版本错误。每当我以为我已经对它有了深刻的理解时,我却发现我仍然大错特错。有人可以帮助我理解为什么重新保存仍然有效吗?

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
1个回答
0
投票

2019 年的 Mongoose 仅具有基本的版本控制支持,该支持至今仍然存在,如下所述:https://mongoosejs.com/docs/guide.html#versionKey.

Mongoose 的作者在他的博客 TheCodeBarbarian 中写道(https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html):

Mongoose 的默认版本控制方案仅在您以“可能不兼容的方式”修改数组时检查文档的版本。

您所做的修改是兼容的,因此没有错误。尝试删除其中一项更新中的评论之一以获取错误。

© www.soinside.com 2019 - 2024. All rights reserved.