node.js - 如何在 NodeJs 中将 Mongo Bulk 与多文档事务一起使用?
问题描述
我想在 mongo 中运行批量操作,但同时在多文档事务中运行它。我正在使用 Meteor 运行 MongoDb 的 NodeJs 驱动程序。
根据 MongoDB 文档(https://docs.mongodb.com/manual/reference/method/Bulk/),应该可以将 和 结合Bulk
起来multi-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();
}
解决方案
我检查了 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();
推荐阅读
- linux - 在同一命令中使用 mapfile 和 awk
- ansible - 如何在 Ansible 自定义事实中以有效 JSON 格式创建动态键/值对列表?
- c# - 如何模拟没有默认构造函数的类
- dart - 如何在 Flutter 中请求 MaterialApp 之外的路由?
- python - 如何制作不规则地理数据的空间图
- python - 无法将“int”对象隐式转换为 str。Python 错误
- typescript - Typescript 示例中的错误
- c# - 在网格视图中显示静态超链接
- jquery - 序列化数组给了我空数组,如何解决?
- javascript - JS - 如何找到最深的一对括号的索引?