Data Model for Coupons storing and redeeming

Hello guys,
The title may be cloudy but here the scenario:

  • Coupons are pre-saved
  • Coupons are unique
  • 1 coupon is only for 1 user
    Here is the code for redeeming:
withTransaction(async (session) => {
 const coupon = await
            referralId: { $exists: false },
          { $set: { referralId: } },
          { session, new: true },

      if (!coupon || !coupon.referralId) {
        throw newError(ErrorCode.INVALID_REQUEST);

      return { code: coupon.code, ok: true };

My problem: I am not sure whether that coupon does not conflict if there are many requests? What is the better approach if I dont want to use retry?
Thank you all for reading. I’m looking forward to your question and response.

Hey guys, actually MongoDB Transaction handles it for me, so there will be no problem, right?

Hi @Thanh_An_Nguy_n,

Welcome to the MongoDB Community forums :sparkles:

Can you provide more details regarding your goals and your issues? For example:

  • Coupons are unique, but you’re worried about conflict. What conflict is this precisely?
  • What does pre-saved mean in your case?
  • Can you post some example documents?
  • Can you post a detailed description of the workflow from start to finish, and where do you foresee an issue?
  • Are you experiencing difficulty with the code you have shared above?

What MongoDB Transaction has handled for you. Can you please provide more details to better understand the issue you are facing?


Hey @Kushagra_Kesav , I have canceled this referral system due to security problem. However, I’m pleased to discuss with you more about this.

Background: We buy 3rd party coupons and insert them to our db, and then let users collect them and redeem.

“pre-saved” means that we have inserted coupons, not generating on users’ demand.

Every coupon is unique and is 1 time use. Meaning that users should not receive the same coupon if the request is duplicated or there are many requests.
Since the filter on query is just like this

So the issue is about concurrent requests and after raising this post, I realized that mongodb transaction has
perfectly handled this case for me.

Thanks for your concern Kushagra.

Thanh An