【问题标题】:Creating a bank transaction with Express, Mongo db使用 Express、Mongodb 创建银行交易
【发布时间】:2022-10-16 16:18:20
【问题描述】:

美好的一天,请我正在尝试编写一个代码,从 mongo db 上的某个帐户文档中删除资金并记入另一个帐户,这样做我正在创建一个交易,我似乎无法弄清楚解决问题的逻辑问题

const Transactions = require("../models/transaction");
const Accounts = require("../models/account");
const { StatusCodes } = require("http-status-codes");
const { BadRequestError, NotFoundError } = require("../errors");

/**
 * Credits an account by an amount
 *
 * @param {String} account_number the account number of the account to be credited
 * @param {Number} amount the amount to be credited
 */
const credit = async (account_number, amount) => {
  return await Accounts.findOneAndUpdate(
    { account_number },
    { $inc: { account_balance: amount } },
    { new: true }
  );
};

/**
 * Debits an account by an amount
 *
 * @param {String} account_number the account number of the account to be debited
 * @param {Number} amount the amount to be debited
 */
const debit = async (account_number, amount) => {
  return await Accounts.findOneAndUpdate(
    { account_number },
    { $inc: { account_balance: -amount } },
    { new: true }
  );
};

const transfer = async (req, res) => {
  // debit the sender
  // credit the recipient
  // create the transaction
  // return a response to throw an error
};

module.exports = { transfer };

这是交易模式

const { Schema, model, Types } = require("mongoose");

var TransactionSchema = new Schema(
  {
    description: {
      type: String,
    },
    amount: {
      type: Number,
      require: true,
    },
    recipient: {
      type: Types.ObjectId,
      ref: "Account",
      required: true,
    },
    sender: {
      type: Types.ObjectId,
      ref: "Account",
    },
    type: {
      type: String,
      enum: ["Debit", "Credit", "Reversal"],
      required: true,
    },
  },
  { timestamps: true }
);

module.exports = model("Transaction", TransactionSchema);

请问如何处理传输逻辑

【问题讨论】:

标签: node.js mongodb express


【解决方案1】:

由于仍未得到答复,因此我将其放在这里以帮助其他可能考虑到该问题已被查看 442 次的人。

现在,这取决于您在哪里、所在国家/地区以及银行系统的运作方式。在我的国家,您总是需要在交易之前生成一个唯一的 sessionID(即在名称验证过程中和在启动转移时生成另一个。假设所有预验证都已完成,您当前的逻辑将需要额外的字段,这将派上用场当您在事务之后执行但应该按原样工作时。但是以下是至关重要的:

  1. 确保执行转移逻辑在交易(ACID)中,这可以防止您在没有相应信用的情况下借记,反之亦然(这肯定会弄乱您的试算表)。见example here!这也会锁定文档以确保在完成(成功或失败)之前不会发生其他事务。
  2. 您应该在您的转账功能中包含费用/扣除。
  3. 如果使用 Mongo 事务,则不需要检查这两个记录之前的余额和之后的余额,以加倍确定。
  4. 您还应该有一个钱包/帐户,这些信用卡和借记卡会在其中保存

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 2011-03-16
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    相关资源
    最近更新 更多