npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

transactions-mongoose

v1.2.7

Published

Transactions for mongoose

Downloads

11

Readme

🇺🇦 Transactions for mongoose

os, nodes npm version Downloads/month Vulnerabilities

Transactions allow you to perform multiple group operations in isolation and undo all operations if one of them fails.

This module allows you to combine different transactions and operations into a group and execute them together. Pre-checks the schema for errors, duplication of unique indexes/fields

Very simple and extremely easy ☕️ :

  • A couple of methods for everything
  • Mix executors as you like
  • Use the session for your usual, standard saving

And yes, let's start!

☕️ buy me a coffee

Installation

First install Node.js and MongoDB. Then:

npm i transactions-mongoose

Mongoose latest also included

Usage

const {Transaction} = require("transactions-mongoose");
const transaction = new Transaction();

// or with debug log
const transaction = new Transaction().setSendbox(true);

An exemplary use case

Create / Insert new document

const {Transaction} = require("transactions-mongoose");
const transaction = new Transaction().setSendbox(true);

const transactionData1 = transaction.add({
    Person,
    firstname: 'Sancho',
    lastname: 'Panse',
    age: 22,
    sex: 'male',
    status: 'free'
});
const transactionData2 = transaction.add({
    Model: 'Person',
    firstname: 'Janna',
    lastname: 'Dark',
    age: 21,
    sex: 'female',
    status: 'free'
});
transaction.add(Person, {
    firstname: 'Hulio',
    lastname: 'Iglessias',
    age: 35,
    sex: 'male',
    status: 'free'
});
await transaction.commit();

console.log('transaction 1 result', transactionData1.result) // the result of the save() operation
console.log('transaction 2 document', transactionData2.document)

Update an existing one

const {Transaction} = require("transactions-mongoose");
const transaction = new Transaction().setSendbox(true);

// variant #1 - use standard setters
let personSancho = await Person.findById('...Sancho id');
personSancho.age += 1;
personSancho.status = 'married';
personSancho.friend_id = '...Hulio Iglessias id';
transaction.add(personSancho);

// variant #2 - by document and update object
let personJanna = await Person.findById('...Janna id');
transaction.add(personJanna).update({
    age: ++personJanna.age,
    status: 'married',
    friend_id: personSancho._id,
    bodyFriend_id: '...Hulio Iglessias id',
});

// variant #3 - by ObjectId
transaction.add(Person, {_id: personSancho._id}).update({
    friend_id: personJanna._id
});
transaction.add({Person, _id: personSancho._id}).update({
    friend_id: personJanna._id
});

await transaction.commit();

Executing an isolated block that may fail is not related to Mongo but affects whether the data is saved or not.

const fetch = require("node-fetch");
const {Transaction} = require("transactions-mongoose");
const transaction = new Transaction().setSendbox(true);

const getAvatar = async (id) => {
    const response = await fetch('https://i.pravatar.cc/300?u=' + id);
    const blob = await response.blob()
    return "data:" + blob.type + ';base64,' + Buffer.from(await blob.arrayBuffer()).toString('base64');
};

const transactionData = transaction.execute(async () => {
    let personSancho = await Person.findById('...Sancho id');
    transaction.add(personSancho).update({
        updatedAt: Date.now(),
        __v: ++personSancho.__v
    });
    // there may be a timeout error or a reader processing error
    personSancho.avatar = await getAvatar(personSancho._id)

    transaction.execute(async () => {
        let personHulio = await Person.findById('...Hulio id');
        personHulio.avatar = await getAvatar(personHulio._id);
        transaction.add(personHulio)
    });

    let personJanna = await Person.findById('...Janna id');
    personJanna.avatar = await getAvatar(personJanna._id);
    const td = transaction.add(personJanna)
    
    // The result can be whatever you want
    // we will return the Janna document update result
    // https://mongoosejs.com/docs/api/query.html#Query.prototype.updateOne()
    return td
});

// and also execute it :)
personJanna.updatedAt = Date.now()
transaction.add(personJanna)

await transaction.commit();
console.log('transaction result', transactionData.result.result);

With session executor

To use with Mongo Replica set

const {Transaction} = require("transactions-mongoose");
const transaction = new Transaction().setSendbox(true);

transaction.session(async (session) => {

    let personSancho = await Person.findById('...Sancho id').session(session);
    let personJanna = await Person.findById('...Janna id').session(session);
    let personHulio = await Person.findById('...Hulio id').session(session);

    personSancho.age = 100; // <-- let's try to make it more mature
    await personSancho.save({session})

    personJanna.age = 100; // <-- let's try to make it more mature too
    await personJanna.save({session})

    personHulio.age = 100; // <-- let's try to make it more mature too
    await personHulio.save({session})

    throw new Error('Test an error - or remark me') // No changes will be saved

    // return result - The result can be whatever you want
    return personJanna
});

await transaction.commit();

If the scheme uses {timestamps: true} in the options, or the fields createdAt (if the document is new), updatedAt (for new and updates) - they will be automatically created or updated updatedAt.