Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PetroGromovo's avatar

How to make working transaction with jenssegers/mongodb working properly ?

In my ubuntu 20 I have MongoDB 6 installed so in mongosh I check test

test> db.version()
6.0.0

In laravel site with jenssegers/mongodb I try to apply transaction and looking at https://github.com/jenssegers/laravel-mongodb/pull/2014 branch in file config/database.php I added replicaSet option :

        'mongodb' => [
         'driver' => 'mongodb',
         'host' => env('DB_HOST', '127.0.0.1'),
         'port' => env('DB_PORT', 27017),
         'database' => env('DB_DATABASE', 'homestead'),
         'username' => env('DB_USERNAME', 'homestead'),
         'password' => env('DB_PASSWORD', 'secret'),
         'options' => [
             'replicaSet' => 'rs',
             'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'),
         ],

         'dsn' => env('MONGO_DB_URI','mongodb://').env('MONGO_DB_HOST', 'localhost')
     ],

Next I run succussfully command

npm install run-rs -g

But I had to run it under sudo.

Next I run :

hoster@hoster-os:/MyProject$ run-rs -v 4.0.0 --shell
Downloading MongoDB 4.0.0
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 67.3M  100 67.3M    0     0  9377k      0  0:00:07  0:00:07 --:--:-- 9339k

I suppose I do not need to install and download MongoDB 4.0.0 So I breaked the command above

hoster@hoster-os:/MyProject$ sudo run-rs -v 6.0.0 --shell
[sudo] password for hoster:
Downloading MongoDB 6.0.0
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   243    0   243    0     0    791      0 --:--:-- --:--:-- --:--:--   791

gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now
Error: Command failed: tar -zxvf mongodb-linux-x86_64-ubuntu1604-6.0.0.tgz

gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now

    at checkExecSyncError (node:child_process:841:11)
    at execSync (node:child_process:912:15)
    at download (/usr/lib/node_modules/run-rs/src/download.js:79:5)
    at run (/usr/lib/node_modules/run-rs/index.js:82:20)
    at run.next (<anonymous>)
    at onFulfilled (/usr/lib/node_modules/run-rs/node_modules/co/index.js:65:19)
    at /usr/lib/node_modules/run-rs/node_modules/co/index.js:54:5
    at new Promise (<anonymous>)
    at co (/usr/lib/node_modules/run-rs/node_modules/co/index.js:50:10)
    at Object.<anonymous> (/usr/lib/node_modules/run-rs/index.js:32:1)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)

I am not sure if I need to run last command ? What is it ? How can I check what I have installed ?

Running my app with

     'replicaSet' => 'rs',

option I got run time error :

MongoDB \ Driver \ Exception \ ConnectionTimeoutException

https://prnt.sc/sOW4R9ckg-db

Without option

     'replicaSet' => 'rs',

I can run my app, so with restarted mongo service :

hoster@hoster-os:/MyProject$ sudo systemctl status  mongod
● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: active (running) since Sat 2022-09-03 07:39:07 EEST; 3s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 14620 (mongod)
     Memory: 193.8M
     CGroup: /system.slice/mongod.service
             └─14620 /usr/bin/mongod --config /etc/mongod.conf

Sep 03 07:39:07 hoster-os systemd[1]: mongod.service: Succeeded.
Sep 03 07:39:07 hoster-os systemd[1]: Stopped MongoDB Database Server.
Sep 03 07:39:07 hoster-os systemd[1]: Started MongoDB Database Server.

having code with error in my control :

  try {
         $session = DB::getMongoClient()->startSession();
         $session->startTransaction();

         $userSubscription = UserSubscription
             ::getBySubscriptionId($subscriptionId)
             ->getByUserId($request->userId)
             ->first();
         if (empty($userSubscription)) {
             $userSubscription = UserSubscription::create([
                 'subscription_id' => $subscriptionId,
                 'user_id'         => $request->userId,
             ]);
         }

         $actionsHistory = \App::make(App\Library\Services\ActionsHistoryServiceInterface::class);
         $ret            = $actionsHistory->addLog(
             model: $useERRORrSubscription,   // LINE WITH NONEXISTING VAR - ERROR WOULD BE RAISED
             action_type: ActionHistoryType:: AHT_USER_SUBSCRIBED_TO_SUBSCRIPTION,
             body:
             ' User ' . $request->userId . '=>' . $user->name . ' (' . $user->email . ') was subscribed to subscription ' . $subscriptionId . '=>' . $subscription->title
         );

         $session->commitTransaction();
     } catch (Exception $e) {
         $session->abortTransaction();

         return response()->json([ 'message' => $e->getMessage() ], HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
     }

Checking /telescope/queries I see only 1 insertOne command and not any transaction commands, as I expected : https://prnt.sc/DtYwx-DS-lUc

What have I to do to run Mongo transaction in my site ?

     laravel/framework "^9.26.1",
     "jenssegers/mongodb": "^3.9.1"

Thanks in advance !

0 likes
11 replies
PetroGromovo's avatar

@vincent15000 You provided a link to under tests. I do not mean tests. In my message I provided a link, but looks like it says about mongo 4, but I have mongo 6. Maybe that makes the difference ?

1 like
PetroGromovo's avatar

@Sinnbeck I have in my app "jenssegers/mongodb": "^3.9.1". PR with your link refs version 3.8. What have I to do ? To waite while this PR would be merged to main branch ?

1 like
PetroGromovo's avatar

I tried to install salvationarinze/laravel-mongodb-transactions with common steps, but got error :

$ composer require salvationarinze/laravel-mongodb-transactions

In PackageDiscoveryTrait.php line 375:
                                                                                                                                                                                                                 
  Could not find a matching version of package salvationarinze/laravel-mongodb-transactions. Check the package 
  spelling, your version constraint and that the package is available in a stability which matches  
   your minimum-stability (dev).                                                                                                                                                                                 
                                                                                                                                                                                                                 

require [--dev] [--dry-run] [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--fixed] [--no-suggest] [--no-progress] [--no-update] [--no-install] [--update-no-dev] [-w|--update-with-dependencies] [-W|--update-with-all-dependencies] [--with-dependencies] [--with-all-dependencies] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--apcu-autoloader-prefix APCU-AUTOLOADER-PREFIX] [--] [<packages>...]

How can I install it ? Some other way ?

1 like
PetroGromovo's avatar

@Sinnbeck In my composer.json I lowered

"jenssegers/mongodb": "^3.8.0",

as this version is compatible with salvation/laravel-mongodb-transactions, but I got next errors :

so composer.json has now :

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^8.0.2",
        "bensampo/laravel-enum": "^5.3",
        "cviebrock/eloquent-sluggable": "^9.0",
        "guzzlehttp/guzzle": "^7.2",
        "jenssegers/mongodb": "^3.8.0",
        "laravel/framework": "^9.26.1",
        "laravel/sanctum": "^3.0",
        "laravel/telescope": "^4.9",
        "laravel/tinker": "^2.7",
        "opcodesio/log-viewer": "^1.2",
        "snipe/banbuilder": "dev-master",
        "spatie/laravel-medialibrary": "^10.0.0"
    },
    "require-dev": {
        "barryvdh/laravel-debugbar": "^3.7",
        "barryvdh/laravel-ide-helper": "^2.12",
        "fakerphp/faker": "^1.9.1",
        "laravel/breeze": "^1.11",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^6.1",
        "phpunit/phpunit": "^9.5.10",
        "sempro/phpunit-pretty-print": "^1.4",
        "spatie/laravel-ignition": "^1.0",
        "squizlabs/php_codesniffer": "*"
    },
    "autoload": {
        "files": [
            "app/Library/helper.php"
        ],

        "psr-4": {
            "App\": "app/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

But next errors :

$ composer require salvation/laravel-mongodb-transactions
Using version dev-master for salvation/laravel-mongodb-transactions
./composer.json has been updated
Running composer update salvation/laravel-mongodb-transactions
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - illuminate/events[v8.0.0, ..., v8.11.2] require php ^7.3 -> your php version (8.1.8) does not satisfy that requirement.
    - Root composer.json requires laravel/telescope ^4.9 -> satisfiable by laravel/telescope[v4.9.0, v4.9.1, v4.9.2, 4.x-dev].
    - laravel/telescope[v4.9.0, ..., 4.x-dev] require laravel/framework ^8.37|^9.0 -> satisfiable by laravel/framework[v9.26.1, v9.27.0, v9.28.0, 9.x-dev].
    - Only one of these can be installed: illuminate/events[v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev], laravel/framework[v9.26.1, v9.27.0, v9.28.0, 9.x-dev]. laravel/framework replaces illuminate/events and thus cannot coexist with it.
    - jenssegers/mongodb[v3.8.0, ..., 3.8.x-dev] require illuminate/events ^8.0 -> satisfiable by illuminate/events[v8.0.0, ..., 8.x-dev].
    - salvation/laravel-mongodb-transactions dev-master requires jenssegers/mongodb 3.8.x -> satisfiable by jenssegers/mongodb[v3.8.0, ..., 3.8.x-dev].
    - Root composer.json requires salvation/laravel-mongodb-transactions dev-master -> satisfiable by salvation/laravel-mongodb-transactions[dev-master].

You can also try re-running composer require with an explicit version constraint, e.g. "composer require salvation/laravel-mongodb-transactions:*" to figure out if any version is installable, or "composer require salvation/laravel-mongodb-transactions:^2.1" if you know which you need.

How that can be fixed ?

Please or to participate in this conversation.