What is a Ledger and why you need to learn about it?
Tags: javascript, mongodb
Published: 2024-06-14 12:05:47

[Portuguese Version](https://daniloab.substack.com/p/o-que-e-ledger-e-por-que-voce-precisa)

## What is Ledger Series
1. [What is a Ledger and why you need to learn about it?](https://dev.to/woovi/what-is-ledger-and-why-does-it-need-idempotence-18n9)
2. [What is Ledger and why does it need Idempotence?](https://dev.to/woovi/what-is-ledger-and-why-does-it-need-idempotence-18n9)
3. [What is a Ledger and Why Floating Points Are Not Recommended?](https://dev.to/woovi/what-is-a-ledger-and-why-floating-points-are-not-recommended-1f4l)

## What is a Ledger?
A ledger, or accounting book, is a financial record that contains all the debit and credit entries of a business. Whether it’s inventory, a warehouse, or a bank account, a ledger is essentially the book where all financial transactions or movements are documented in an organized and chronological manner. Each entry in the ledger is called a journal entry, which can include various transactions such as sales, purchases, payments, and receipts.

## How Did It Originate?
The earliest records of accounting appeared in ancient civilizations such as Mesopotamia, where clay tablets were used to record commercial transactions. During the Middle Ages, accounting evolved significantly in Europe, culminating with the Italian monk and mathematician Luca Pacioli, who documented the revolutionary double-entry system in his book "Summa de Arithmetica, Geometria, Proportioni et Proportionalità" in 1494. This system, which records each transaction in two accounts (debit and credit), formed the basis of modern accounting. With the digital era, automated systems replaced traditional ledgers, and more recently, blockchain technology introduced distributed ledgers, offering greater security and transparency. Today, ledgers are fundamental to the integrity of financial transactions and the efficient management of resources worldwide.

![Summa arithmetic original book cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/acjhjta9a7fyzsl29yj1.png)


## How Does It Work?
The operation of a ledger is relatively simple. Each financial transaction is recorded in a double-entry system—this means that for every debit, there is a corresponding credit. For example, if a company makes a sale on credit, it debits the accounts receivable (asset) and credits the revenue account (income). This method ensures that the accounting is always balanced, with the sum of debits equaling the sum of credits.

## How Do Financial/Banking Institutions Use the Ledger?
Financial and banking institutions use ledgers to record all daily transactions. These records include deposits, withdrawals, transfers, loan payments, and interest, among others. Ledgers help maintain transparency, traceability, and integrity of financial records, facilitating audits and ensuring regulatory compliance.

## Calculating the Bank Balance with JavaScript and MongoDB
To calculate the bank balance quickly and efficiently, a common approach is to keep the balance updated in the last entry of the ledger. Let’s illustrate this with an example in JavaScript and MongoDB.

1. Define the structure of the ledger in MongoDB:
```ts
{
  _id: ObjectId("60c72b2f9b1d8e4d2f507d3a"),
  date: ISODate("2023-06-13T12:00:00Z"),
  description: "Deposit",
  amount: 1000.00,
  balance: 1000.00
}
```

2. Function to add a new entry to the ledger and calculate the balance:
```ts
const { MongoClient } = require('mongodb');

async function addTransaction(description, amount) {
  const url = 'mongodb://localhost:27017';
  const client = new MongoClient(url);
  
  try {
    await client.connect();
    const database = client.db('finance');
    const ledger = database.collection('ledger');

    const lastEntry = await ledger.find().sort({ date: -1}).limit(1).toArray();

    const lastBalance = lastEntry.length > 0 ? lastEntry[0].balance : 0;

    const newBalance = lastBalance + amount;

    const newEntry = {
      date: new Date(),
      description: description,
      amount: amount,
      balance: newBalance
    };

    await ledger.insertOne(newEntry);

    console.log('Transaction successfully added:', newEntry);
  } finally {
    await client.close();
  }
}

addTransaction('Deposit', 500.00);
```

**What We're Doing in the Above Example:**
1. Connect to the DB
2. Access the Ledger collection
3. Get the last entry
4. Retrieve the first item of the array sorted by the most recent
5. Calculate the balance
6. Insert the new entry into the collection

## Conclusion
The above code is a simple representation of how to implement a ledger and is far from ideal. In the real world, you need to address issues such as:

- Eventual consistency
- Concurrency
- Idempotency

And many other classic IT challenges.

With this in mind, to design a good ledger, you should at least be able to handle the three topics mentioned above.

So, do you think you can write a ledger?

What would you improve in the above, simplified example?

How would you handle debits? Refunds? Future transactions?

All these challenges are great and occur daily in any field we work in. That's why, in my opinion, you should learn about ledgers.

Learning about ledgers forces you to learn numerous other concepts that will help you find solutions to various problems and will definitely make you stand out in your career.

---

If you want to work in a startup in its early stages, This is your chance. [Apply today!](https://woovi.com/jobs/)

---

Visit us [Woovi](https://woovi.com/)!

---

Follow me on [Twitter](https://x.com/daniloab_)

If you like and want to support my work, become my [Patreon](https://www.patreon.com/daniloab)

Want to boost your career? Start now with my mentorship through the link

https://mentor.daniloassis.dev

See more at https://linktr.ee/daniloab

Photo of <a href="https://unsplash.com/pt-br/@stellrweb?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">StellrWeb</a> on <a href="https://unsplash.com/pt-br/fotografias/caixa-registadora-canon-branca-djb1whucfBY?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>