0

我正在使用 Feathers 4.5.0 和 Mongo 5.0.2 。我想对集合执行 Mongo DB 事务。我将feather-mongoose文档中的示例复制到我的服务挂钩中。

const TransactionManager = require('feathers-mongoose').TransactionManager;
const isTransactionEnable = process.env.TRANSACTION_ENABLE || false;
const skipPath = ['login'];

let moduleExports = {
  before: {
  all: [],
  find: [],
  get: [],
  create: [
    when(isTransactionEnable, async hook =>
     TransactionManager.beginTransaction(hook, skipPath)
   )
  ],
  update: [
   when(isTransactionEnable, async hook =>
     TransactionManager.beginTransaction(hook, skipPath)
   )
  ],
  patch: [],
  remove: []
},

after: {
  all: [],
  find: [],
  get: [],
  create: [when(isTransactionEnable, TransactionManager.commitTransaction)],
  update: [when(isTransactionEnable, TransactionManager.commitTransaction)],
  patch: [],
  remove: []
},

error: {
  all: [],
  find: [],
  get: [],
  create: [when(isTransactionEnable, TransactionManager.rollbackTransaction)],
  update: [when(isTransactionEnable, TransactionManager.rollbackTransaction)],
  patch: [],
  remove: []
 }
};

module.exports = moduleExports;

我收到此错误消息ReferenceError: when is not defined。我删除了“何时”,交易仍然没有工作。

4

1 回答 1

0

如果您在本地设置 MongoDB 副本时遇到问题,当我浏览这个问题时,这个 youtube 教程对我很有用。您的副本数据库必须在 feather-mongoose TransactionManger 可以完成其工作之前工作。我对示例代码做了一些调整

const TransactionManager = require('feathers-mongoose').TransactionManager;
const isTransactionEnable = process.env.TRANSACTION_ENABLE || false;
const skipPath = ['login'];


module.exports = {
  before: {
  all: [],
  find: [],
  get: [],
  create: [(isTransactionEnable, async hook =>
    TransactionManager.beginTransaction(hook, skipPath)
  )],
  update: [(isTransactionEnable, async hook =>
    TransactionManager.beginTransaction(hook, skipPath)
  )],
  patch: [(isTransactionEnable, async hook =>
    TransactionManager.beginTransaction(hook, skipPath)
  )],
  remove: []
},

after: {
  all: [],
  find: [],
  get: [],
  create: [(isTransactionEnable, async () => {await TransactionManager.commitTransaction;})],
  update: [(isTransactionEnable, async () => {await TransactionManager.commitTransaction;})],
  patch: [(isTransactionEnable, async () => {await TransactionManager.commitTransaction;})],
  remove: []
},

error: {
  all: [],
  find: [],
  get: [],
  create: [(isTransactionEnable, async () => {await TransactionManager.rollbackTransaction;})],
  update: [(isTransactionEnable, async () => {await TransactionManager.rollbackTransaction;})],
  patch: [(isTransactionEnable, async () =>{await TransactionManager.rollbackTransaction;})],
  remove: []
}
};

进行这些更改后,我在更新用户集合时触发了错误,TransactionManger 按预期工作

 const newUser = app.service('users').create({name:'ope', gender:'Male')}
 app.service('users').patch(newUser._idl,{gender: 'Female'}); //this fails and transaction rollback users collection to initate state. 

这行代码将失败,因为它期望 newUser._id 但提供了 newUser._idl。因此,用户“ope”将从数据库中删除。我希望这可以帮助别人。

于 2021-09-06T17:12:45.690 回答