loopback-connector-mongodb icon indicating copy to clipboard operation
loopback-connector-mongodb copied to clipboard

mongodb transaction support?

Open melochale opened this issue 7 years ago • 14 comments

mongodb has multiple-documents transaction feature since version 4.0, how dose this project support or how do we use transaction api with loopback? thanks!

melochale avatar Dec 11 '18 07:12 melochale

@raymondfeng, could you please help with this question? Thanks.

dhmlau avatar Feb 12 '19 04:02 dhmlau

Any update on this issue?

chi-tran avatar Feb 15 '19 05:02 chi-tran

is anyone working on this? is it possible in the near future?

webocs avatar Feb 20 '19 18:02 webocs

Hello, guys, I wrote some codes to resolve this problem temporarily

function Transaction(Model) {
  this.Model = Model;
  this.isInTransation = false;
}

Transaction.prototype.start = function() {
  let self = this;
  let connector = self.Model.getDataSource().connector;
  if (connector.name !== 'mongodb') {
    throw new tools.createError(500, 'Only support mongodb database transaction');
  }
  else {
    if (!self.isInTransation) {
      self.session = connector.client.startSession();
      self.session.startTransaction();
      self.isInTransation = true;
    } 
    return self.session;
  }
};

Transaction.prototype.commit = async function() {
  let self = this;
  if (self.isInTransation) {
    await self.session.commitTransaction();
    self.session.endSession();
    self.isInTransation = false;
  }
};

Transaction.prototype.rollback = async function() {
  let self = this;
  if (self.isInTransation) {
    await self.session.abortTransaction();
    self.session.endSession();
    self.isInTransation = false;
  }

};

module.exports = Transaction;

The usage as following:

let transaction = new Transaction(Model);
let session = tranaction.start();
try {
  // do something with session collection not the LOOPBACK MODEL,
  // like session.collection('<CollectionName>').insertOne()
  await transction.commit();
// callback()
}
catch (e) {
  await transction.rollback();
  // callback()
}

melochale avatar Feb 21 '19 03:02 melochale

Looks good, I've been thinking about doing something like that. I'm not sure if trying to add this to the connector is worth it. I can't find a roadmap, so I'm not sure if this is getting ditched when LB4 comes out and LB3's LTS ends

webocs avatar Feb 24 '19 02:02 webocs

@melote @webocs, please feel free to submit a PR for adding the transaction support. Currently, the connectors are shared by LB3 and LB4.

cc @raymondfeng

dhmlau avatar Feb 24 '19 14:02 dhmlau

I understand starting the transaction. But how do I update a collection with a reference to the transaction object?

I updated a collection after the transaction started, but it is already committed.

chi-tran avatar Mar 25 '19 06:03 chi-tran

Hi,

Should we pass options here to allow attach session:

  this.execute(modelName, 'insertOne', data, Object.assign({safe: true}, options), function(err, result) {

So in LoopBack 4, we can easily propagate transaction:

const session = dataSource.connector.client.startSession();
session.startTransaction();

userRepository.create(user, {session});

await session.commitTransaction();
session.endSession();

We also have to create collection before running operations.

hoangleanhtu avatar Jun 01 '19 10:06 hoangleanhtu

I implemented one as above suggestion hoangleanhtu/loopback-connector-mongodb.

@transactional decorator in this library supports MongoDB as well:

// Import here...
import {transactional} from "loopback4-spring";
 
export class UserService {
 
    constructor(
        @repository(UserRepository)
        private userRepository: UserRepository,
        @repository(CustomerRepository)
        private customerRepository: CustomerRepository
    ) {
    }
 
    @transactional()
    async create(
        user: User,
        customer: Customer,
        throwError: boolean,
        options?: Object // Options is populated by @transactional
    ): Promise<{user: User, customer: Customer}> {
 
        // Must pass options to propagate transaction
        await this.userRepository.create(user, options);
        await this.customerRepository.create(customer, options);
 
        if (throwError) {
            throw new Error('Error after create user & customer. Transaction is rollback.')
        }
 
        return {user, customer};
    }
}

hoangleanhtu avatar Jun 03 '19 06:06 hoangleanhtu

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Aug 28 '19 01:08 stale[bot]

This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.

stale[bot] avatar Sep 11 '19 02:09 stale[bot]

Hello, will we have an official release of this?

alansoliditydev avatar Apr 15 '20 16:04 alansoliditydev

Hello, guys, I wrote some codes to resolve this problem temporarily

function Transaction(Model) {
  this.Model = Model;
  this.isInTransation = false;
}

Transaction.prototype.start = function() {
  let self = this;
  let connector = self.Model.getDataSource().connector;
  if (connector.name !== 'mongodb') {
    throw new tools.createError(500, 'Only support mongodb database transaction');
  }
  else {
    if (!self.isInTransation) {
      self.session = connector.client.startSession();
      self.session.startTransaction();
      self.isInTransation = true;
    } 
    return self.session;
  }
};

Transaction.prototype.commit = async function() {
  let self = this;
  if (self.isInTransation) {
    await self.session.commitTransaction();
    self.session.endSession();
    self.isInTransation = false;
  }
};

Transaction.prototype.rollback = async function() {
  let self = this;
  if (self.isInTransation) {
    await self.session.abortTransaction();
    self.session.endSession();
    self.isInTransation = false;
  }

};

module.exports = Transaction;

The usage as following:

let transaction = new Transaction(Model);
let session = tranaction.start();
try {
  // do something with session collection not the LOOPBACK MODEL,
  // like session.collection('<CollectionName>').insertOne()
  await transction.commit();
// callback()
}
catch (e) {
  await transction.rollback();
  // callback()
}

Would this work with loopback 4?

me1go avatar Aug 11 '20 15:08 me1go

Hello, guys, I wrote some codes to resolve this problem temporarily

function Transaction(Model) {
  this.Model = Model;
  this.isInTransation = false;
}

Transaction.prototype.start = function() {
  let self = this;
  let connector = self.Model.getDataSource().connector;
  if (connector.name !== 'mongodb') {
    throw new tools.createError(500, 'Only support mongodb database transaction');
  }
  else {
    if (!self.isInTransation) {
      self.session = connector.client.startSession();
      self.session.startTransaction();
      self.isInTransation = true;
    } 
    return self.session;
  }
};

Transaction.prototype.commit = async function() {
  let self = this;
  if (self.isInTransation) {
    await self.session.commitTransaction();
    self.session.endSession();
    self.isInTransation = false;
  }
};

Transaction.prototype.rollback = async function() {
  let self = this;
  if (self.isInTransation) {
    await self.session.abortTransaction();
    self.session.endSession();
    self.isInTransation = false;
  }

};

module.exports = Transaction;

The usage as following:

let transaction = new Transaction(Model);
let session = tranaction.start();
try {
  // do something with session collection not the LOOPBACK MODEL,
  // like session.collection('<CollectionName>').insertOne()
  await transction.commit();
// callback()
}
catch (e) {
  await transction.rollback();
  // callback()
}

@melochale did you raise the PR for loopback3

MrShadow50 avatar Aug 08 '24 08:08 MrShadow50