0

The MongoDB with the dart server doesn't have the transaction feature (ref).

What method that I can be using for this situation?

The user is buying the product. The server will check the product is available/enabled. Then check the user is available/enabled. Then check the balance if the user that more than the product price. After that, update the new balance of the user and create a new order.

code example:

Future<bool> theUserBuyProduct(uid, productId) async {
  await transactionOpen();

  try {
    //Check the product is available/enabled.
    DbCollection productCollection = MongodbDatabase.db.collection('product');
    Map<String, dynamic>? productData =
        await productCollection.findOne(where.eq('productId', productId).eq('isEnable', true));
    double productPrice = double.tryParse((productData?['price']).toString()) ?? 0; //The `productPrice` will be used.
    if (productPrice <= 0) {
      await cancelTransaction();
      return false;
    }

    //Check the user is available/enabled and that this user has a balance of more than the product price.
    DbCollection userCollection = MongodbDatabase.db.collection('user');
    Map<String, dynamic>? userData = await userCollection.findOne(where.eq('uid', uid).eq('isEnable', true));
    double userBalance = double.tryParse((userData?['balance']).toString()) ?? 0;
    double newBalance = userBalance - productPrice; //The `newBalance` will be used.
    if (newBalance < 0) {
      await cancelTransaction();
      return false;
    }

    //Update new balance of the user after deduction.
    await userCollection.updateOne(where.eq('uid', uid), modify.set('balance', newBalance));

    //Create a new order for this user.
    DbCollection orderCollection = MongodbDatabase.db.collection('order');
    await orderCollection.insertOne({'uid': uid, 'productId': productId, 'createAt': DateTime.now()});
  } catch (e) {
    await cancelTransaction();
    return false;
  }

  await submitTransaction();
  return true;
}

0 Answers0