node.js - 如何在 Node Js 中使用 Mongodb Bulk 和多文档事务?

标签 node.js mongodb meteor bulkinsert

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

根据 MongoDB 文档 ( https://docs.mongodb.com/manual/reference/method/Bulk/ ),应该可以将批量多文档事务结合起来。但是,我一直无法解决这个问题。

我的问题是如何将 session 对象传递给批量操作。对于非批量操作,我们只需将其作为选项对象 const options = {session: session} 传递。我尝试了多种方法,但似乎都不起作用。

如何在批量操作中使用session对象?

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

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();
}

最佳答案

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

execute 方法的定义如下:

execute(_writeConcern, 选项, 回调);

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

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

关于node.js - 如何在 Node Js 中使用 Mongodb Bulk 和多文档事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59908071/

相关文章:

node.js - 从 ReactJS 组件调用服务器端函数

javascript - Webscraper 函数返回未定义

javascript - MongoDB .find 在 shell 中有效,但在 js 中无效

mongodb - 仅当所有字段都唯一时才将文档插入 MongoDB

Meteor,为什么散列后相同的密码,不同的字符串存储在数据库中

node.js - 自适应卡上的 Action.Submit 不会调用下一步(仅在 Microsoft Teams 中不起作用,在网络聊天中起作用): Bot Framework V4

scala - 将 Salat 与 MongoDB 一起使用时,处理复合键的最佳方法是什么?

c# - 如何使用 MongoDB C# 将新对象插入(推送)到嵌套数组中?

meteor - 在事件链接的路由更改上重新运行辅助函数

javascript - meteor 设计模板