【问题标题】:Mongodb Transactions - Unable to read from a snapshotMongodb 事务 - 无法从快照中读取
【发布时间】:2021-02-05 21:08:40
【问题描述】:

我正在尝试使用 mongoose 进行 MongoDB 事务,但在每次创建数据库并插入用户和公司的请求时,我都会收到以下错误

“由于未决的集合目录更改,无法从快照中读取;请重试该操作。快照时间戳为 Timestamp(1584451745, 1)。集合最小值为 Timestamp(1584451753, 1)”

在重试请求时它会起作用。但是当我发送一个新的请求来创建一个新的数据库并插入一个用户和一个公司时,我得到了同样的错误。我总是需要重试请求才能成功插入数据。

const session = await mongoose.startSession();
session.startTransaction();

try {
  await db.createCollection("users");
  await db.createCollection("companies");

  const savedUser = await UserModel({
    ...userDetails,
  }).save({ session });


  const company = await new CompanyModel({
    ...companyDetails
  }).save({ session });


  await session.commitTransaction();

  return { message: "User Added Successfully" };

} catch (err) {
  error("Transaction Error", err);
  await session.abortTransaction();
  throw err;
} finally {
  session.endSession();
}

知道我在这里缺少什么吗?

【问题讨论】:

  • 为什么需要为每个请求创建一个集合users
  • @WanBachtiar 实际上我正在为每个请求创建一个新数据库,因此在插入数据之前需要创建一个用户集合和公司集合(我错过了公司模型的集合创建代码,我已经更新我的问题 sn-p)
  • @WanBachtiar 还更新了问题,以便更好地理解场景。
  • 你能用 createCollection() 选项writeConcern: "majority" 进行测试吗?见docs.mongodb.com/manual/reference/method/db.createCollection/…
  • 有人找到解决办法了吗?

标签: node.js mongodb mongoose transactions


【解决方案1】:

好的,我想通了。根据 mongoose 文档,您需要在使用事务之前创建集合:

Model.createCollection()
Parameters
[options] «Object» see MongoDB driver docs
[callback] «Function»
Create the collection for this model. By default, if no indexes are specified, mongoose will not create the collection for the model until any documents are created. Use this method to create the collection explicitly.

Note 1: You may need to call this before starting a transaction See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations

来源:https://mongoosejs.com/docs/api.html#model_Model.createCollection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2020-12-30
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    相关资源
    最近更新 更多