mongoose-transact-utils
TypeScript icon, indicating that this package has built-in type declarations

0.1.2 • Public • Published

mongoose-transact-utils

Helper methods for Mongoose and MongoDB transactions (Check out this medium post to know more about it).

The library comes with @types for Typescript users.

NPM Version

Installation

npm i mongoose-transact-utils

OR

yarn add mongoose-transact-utils

API Reference and Examples

API Reference - Docs

A simple use case for transaction

const { runInTransaction } = require('mongoose-transact-utils');
 
const { User } = require('./models');
 
// any queries or write you want to do using transaction
(async () => {
  // runInTransction catches any error in the callback to abort the transaction session
  // and then rethrows the error for you to handle the reporting
  await runInTransaction(async session => {
    // run any queries here
    await addFriend('John', 'Jane', session);
  });
 
  console.log('John and Jane are friend now!');
})();
 
async function addFriend(nameA, nameB, session) {
  const userA = await User.find({ name: nameA }).session(session);
  const userB = await User.find({ name: nameB }).session(session);
 
  userA.friends.push(userB._id);
  userB.friends.push(userA._id);
 
  await userA.save();
  await userB.save();
}

Contributing

We are more than happy to accept contributions to this project in form of feedback, bug reports and pull requests.

References:

Contributors

Package Sidebar

Install

npm i mongoose-transact-utils

Weekly Downloads

9

Version

0.1.2

License

MIT

Unpacked Size

8.51 kB

Total Files

6

Last publish

Collaborators

  • drenther
  • nitish-mehta