首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >与Express创建银行事务,Mongo db

与Express创建银行事务,Mongo db
EN

Stack Overflow用户
提问于 2022-02-21 14:09:47
回答 1查看 593关注 0票数 0

你好,我正在尝试写一段代码,从mongo db上的某个帐户文档中移除金钱,并将其贷记到另一个帐户中。在这样做的过程中,我创建了一个事务,我似乎无法理解解决这个问题的逻辑。

代码语言:javascript
复制
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 };

这是事务模式。

代码语言:javascript
复制
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);

我如何处理传送逻辑?

EN

回答 1

Stack Overflow用户

发布于 2022-10-16 08:18:20

现在这取决于你在哪里,国家,以及银行系统是如何运作的。在我的国家,您总是需要在事务之前生成一个唯一的sessionID (即在名称验证过程中,在启动传输时生成另一个)。假设所有的预验证都已经完成,那么您当前的逻辑将需要额外的字段,这些字段在事务完成后会派上用场,但应该按原样工作。然而,以下各点至关重要:

  1. 确保您在事务(ACID)中执行传输逻辑,这可以防止出现借方没有相应的信贷或反之亦然的情况(这肯定会破坏您的试算表)。参见这里的示例(https://www.ultimateakash.com/blog-details/IiwzQGAKYAo=/How-to-implement-Transactions-in-Mongoose-&-Node.Js-(Express%29)!,这也锁定了文档,以确保在完成之前不会发生其他事务(成功或失败)。
  2. 你应该在你的转帐函数中包括费用/扣减。
  3. 如果使用Mongo交易的话,没有什么必要--在这两项记录之前检查余额,然后再检查余额,这是双重肯定的。
  4. 您还应该有一个钱包/帐户,在那里这些贷项和借方是持久化的。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71207726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档