【发布时间】: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);
请问如何处理传输逻辑
【问题讨论】:
-
一些有用的信息:(1)What is a database transaction(2)MongoDB Transactions(3)我想你想在一个交易中对两个账户进行借记和贷记。