【问题标题】:How to use Mongo Bulk together with multi-document transactions in NodeJs?如何在 Node Js 中将 Mongodb Bulk 与多文档事务一起使用?
【发布时间】:2020-01-26 20:09:37
【问题描述】:

我想在 mongo 中运行批量操作,但同时在多文档事务中运行它。我正在使用 Meteor 运行 MongoDb 的 NodeJs 驱动程序。

根据 MongoDB 文档 (https://docs.mongodb.com/manual/reference/method/Bulk/),应该可以组合 Bulkmulti-document transactions。但是,我无法解决这个问题。

我的问题是如何将session 对象传递给批量操作。对于非批量操作,我们只需将其作为选项对象 const options = {session: session} 传递。我尝试通过多种方式通过它,但似乎没有任何效果。

session 对象应该如何在Bulk 操作中使用?

下面是我想要实现的一个简单示例。

const getMongoClient = function() {
  const { client } = MongoInternals.defaultRemoteCollectionDriver().mongo;
  return client;
}


const session = client.startSession();
try {
  session.startTransaction();
  const bulk = someCollectionToBulkWrite.rawCollection().initializeOrderedBulkOp(); // Pass the session here?

  const dataInsert = someCollection.insert(someObject, {session}).await().value;
  const dataInsertOtherDocument = someOtherCollection.insert(someOtherObject, {session}).await().value;

  bulk.find( { _id: someId } ).update( { $set: { testField: 3}}); //Or pass the session here?
  bulk.find( { _id: someOtherId } ).update( { $set: { testField: 3}});

  bulk.execute().await(); // Or pass the session here?

  session.commitTransaction().await();
} finally {
  session.endSession();
}

【问题讨论】:

    标签: node.js mongodb meteor bulkinsert


    【解决方案1】:

    我检查了用于 NodeJS 的 MongoDB 驱动程序的代码,更具体地说,检查了 Bulk API (https://github.com/mongodb/node-mongodb-native/blob/master/lib/bulk/common.js)

    execute 方法的定义如下:

    execute(_writeConcern, options, callback);

    因此会话应该作为第二个参数传递给execute。在问题中提供的示例中,如下所示:

    bulk.execute(null, {session}).await();

    【讨论】:

    • 链接不可用@Euklides
    猜你喜欢
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2014-02-14
    • 2012-11-22
    相关资源
    最近更新 更多