Good day, please I am trying to write a code that removes money from a certain account document on mongo db and credits the other account, in doing this I am creating a transaction, I can't seem to figure out the logic to solve the problem
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 };
This is the transaction schema
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);
How do I please handle the transfer logic