Need help regarding transaction with pm2 in parse server

Hello,

I am now using pm2 in my Parse Server (version 5) cloud, and with mongodb as database. I have below code:

  const query = new Parse.Query('FinanceReport');
  query.equalTo('businessDay', businessDay).equalTo('merchantId', levelInfo.merchantId);
  let currentFinanceReport = null;
  const financeReportList = await query.find();
  if (financeReportList.length === 0) {
    query.lessThan('businessDay', businessDay);
    query.descending('businessDay');
    const lastFinanceReport = await query.first();
    currentFinanceReport = new Parse.Object('FinanceReport');
    currentFinanceReport.set('scope', levelInfo.scope);
    currentFinanceReport.set('dayCount', 0);
    currentFinanceReport.set('dayAmount', 0);
    if (!lastFinanceReport) {
      currentFinanceReport.set('currentAmount', 0);
      currentFinanceReport.set('currentCount', 0);
    } else {
      currentFinanceReport.set('currentAmount', lastFinanceReport.get('currentAmount'));
      currentFinanceReport.set('currentCount', lastFinanceReport.get('currentCount'));
    }
  } else {
    [currentFinanceReport] = financeReportList;
  }
  ......
  // there will be the save logic for currentFinanceReport to the mongodb 
  ......

Just a bit explanation: I just would like to have ONLY ONE FinanceReport record added for everyday. But if there are more than 2 processes (managed by pm2) run the above code just at the same time for the same merchant, there will be 2 records for the same day saved to the database. Although this does not happen frequently, it is indeed a serious bug for us.

How should I resolve such problem? Could any one please kindly help?

Great thanks!

Best regards, Jason

Maybe you should create unique index on your database with key (merchantId, businessDay) - it won’t allow you to save 2 the same reports.

2 Likes

Not sure how PM2 works, but you can use the NodeJS cluster module to determine a worker ID and only run the function if the cluster is #1. Alternatively you can create a single core worker server to avoid this issue

1 Like

Hi @avramo ,

Yes and thanks for your kind help, actually I have posted this possible solution below with other related issues: