来自 withTransaction 回调的 Mongoose return 值
Mongoose return value from withTransaction callback
我想利用 mongoose 的 withTransaction
助手,特别是因为它能够自动重试瞬态事务错误。但是,withTransaction
helper 似乎无法返回数据,这对我来说是个问题。
我的代码如下所示:
import { startSession } from 'mongoose';
async addItem(itemData) {
const session = await startSession();
session.startTransaction();
try {
const item = await new Item({ itemData }).save({ session });
// a bunch of other async operations...
await session.commitTransaction();
session.endSession();
return item;
} catch (error) {
await session.abortTransaction();
session.endSession();
throw error;
}
}
我怎样才能 (1) 使用 withTransaction
帮助程序但仍让此函数像当前一样返回 item
,或者 (2) 使此函数自动重试瞬态事务错误通过使用 withTransaction
.
以外的其他方式
这似乎是节点驱动程序中的 known issue。该票证中提供了一些解决方法。
我写了一个简单的助手,在内部使用 withTransaction
来解决问题,并使 mongoose 的交易变得不那么冗长。
安装后 mongoose-trx 你可以简单地做:
const transaction = require('mongoose-trx');
const [customer] = await transaction(session => Customer.create([{ name: 'Test' }], { session }));
// do whatever you need to do with the customer then return it
它也支持交易选项,请参阅有关如何操作的文档。
我想利用 mongoose 的 withTransaction
助手,特别是因为它能够自动重试瞬态事务错误。但是,withTransaction
helper 似乎无法返回数据,这对我来说是个问题。
我的代码如下所示:
import { startSession } from 'mongoose';
async addItem(itemData) {
const session = await startSession();
session.startTransaction();
try {
const item = await new Item({ itemData }).save({ session });
// a bunch of other async operations...
await session.commitTransaction();
session.endSession();
return item;
} catch (error) {
await session.abortTransaction();
session.endSession();
throw error;
}
}
我怎样才能 (1) 使用 withTransaction
帮助程序但仍让此函数像当前一样返回 item
,或者 (2) 使此函数自动重试瞬态事务错误通过使用 withTransaction
.
这似乎是节点驱动程序中的 known issue。该票证中提供了一些解决方法。
我写了一个简单的助手,在内部使用 withTransaction
来解决问题,并使 mongoose 的交易变得不那么冗长。
安装后 mongoose-trx 你可以简单地做:
const transaction = require('mongoose-trx');
const [customer] = await transaction(session => Customer.create([{ name: 'Test' }], { session }));
// do whatever you need to do with the customer then return it
它也支持交易选项,请参阅有关如何操作的文档。