Search code examples
node.jsmongodbtransactions

Nodejs mongodb's Transaction API `withTransaction` always return null


I would like to return certain result from mongodb's withTransaction function. However, I can't seem to return anything except null from it.

It's documented in the official documentation that a promise should be returned.

https://mongodb.github.io/node-mongodb-native/3.3/api/ClientSession.html

IMPORTANT: This method requires the user to return a Promise, all lambdas that do not
return a Promise will result in undefined behavior.

index.js

const mongodb = require('mongodb');

(async() => {
  const client = await mongodb.connect(url);
  const db = await client.db("testt");
  const session = client.startSession()

  const res =   session.withTransaction(async function() {
      return new Promise((resolve, reject) => {
        if(true) {
          resolve('laughed')
        } else {
          reject(`not laughing`);
        }
    })
  })
  console.log('result here')   //result here
  console.log(res)             //Promise { <pending> }
  console.log(await res);      //null
}) ()

Edit: Since async function always return Promise. I replaced the the new Promise() with a simple string, but the result is exactly the same, which is confusing.

const res =   session.withTransaction(async function() {
  return `laughed`
})

Solution

  • It's documented in the official documentation that a promise should be returned.

    The documentation says (emphasis mine):

    IMPORTANT: This method requires the user to return a Promise, all lambdas that do not return a Promise will result in undefined behavior.

    There is no claim that the promise which you return from your callback will be returned from withTransaction. I do not see any description of withTransaction's return value at all.

    The current implementation appears to return the result of commitTransaction as the return value of withTransaction, and that result appears to be null in case of a successful commit.

    I believe the result of the promise that your application is giving to the driver is discarded here.

    So, the driver appears to behave as documented.

    This behavior change was requested here.