🖊️Working with Managed Database

In this guide, you'll learn how to perform CRUD (Create, Read, Update, Delete) operations on your Blockflow Managed Databases. The process involves the following steps:

  1. Initialize the Database Connection

  2. Perform CRUD Operations

Initialize the Database Connection

To interact with your Managed Database, you need to initialize a database connection within your Instance or API logic.

Blockflow provides a bind function that allows you to establish a connection to your database.

First, import the necessary dependencies:

import { IEventContext, IBind } from "@blockflow-labs/utils";

export const handler = async (context: IEventContext, bind: IBind) => {
  // Implement your event handler logic for Issue here 
}

Then, in your event handler function in the instance logic, initialize the database connection using the bind function:

export const handler = async (context: IEventContext, bind: IBind) => {
  // Implement your event handler logic for Issue here 
}

bind is your gateway to the managed database.

To initialize the database connection for the database named "Balances" in your Instance:

import { IEventContext, Instance, IBind } from "@blockflow-labs/utils";

export const handler = async (context: IEventContext, bind: IBind) => {
  // Implement your event handler logic for Issue here 
  const balancesDB: Instance = bind(Balances);
}
  • Inside the event handler function, we initialize the database connection by calling bind("Balances") and assign it to the balancesDB variable.

  • We can then use the balancesDB connection to perform various database operations using the available methods.

  • Make sure to replace "Balances" with the actual name of your database.

Perform CRUD Operations

Once you have initialized the database connection, you can perform various CRUD operations using the MongoDB-compatible methods provided by Blockflow.

Example: Combining CRUD Operations

const balancesDB: Instance = bind(Balances);
const user = "0xdac17f958d2ee523a2206206994597c13d831ec7";
let userBalance = await balancesDB.findOne({id: user.toLowerCase()});
if(!userBalance) userBalance = await balancesDB.create({id: user.toLowerCase()});

In this example, we demonstrate how to combine different CRUD operations to handle a specific use case:

  1. We initialize the balancesDB connection using bind("Balances").

  2. We define a user variable to store the Ethereum address of the user we want to query or create.

  3. We use the findOne method to check if a document with the specified id (converted to lowercase) exists in the database. This is a read operation.

  4. If the userBalance document doesn't exist (!userBalance), we create a new document using the create method, passing an object with the id (converted to lowercase) and an initial balance field set to "0". This is a create operation.

After this, we can perform further operations with the userBalance document, such as updating the balance or reading other fields.

Creating Documents

To create a new document in your database, use the create method:

const newUser = await db.create({
  id: "user123",
  name: "John Doe",
  email: "john@example.com"
});

Reading Documents

To retrieve documents from your database, you can use methods like findOne or find:

// Find a single document by ID
const user = await db.findOne({ id: "user123" });

// Find multiple documents based on a query
const activeUsers = await db.find({ status: "active" });

Updating Documents

To update existing documents in your database, you can use methods like updateOne, updateMany, or save.

  userBalance.balance = new BigNumber("1").toString();
  await balancesDB.save(userBalance);

Deleting Documents

To delete documents from your database, use the deleteOne or deleteMany methods:

await balancesDB.deleteOne({id: user.toLowerCase()});

Best Practices

  • Use lowercase for the id field to ensure consistent querying and indexing. If it doesn't exist it creates an empty Mongo document and returns it.

  • Include appropriate error handling and data validation in your code.

  • Consider using transactions when performing multiple database operations that need to be atomic.

  • You can use various MongoDB functions like findOne(), updateOne(), save(), insertMany(), exists(), updateMany(), findOneAndUpdate(), replaceOne(), findOneAndReplace(), deleteOne(), deleteMany(), findOneAndDelete() for performing CRUD operations on your managed database.

  • Make sure to use await before calling any of the aforementioned methods, as all of them return a promise. This ensures that the operation completes before proceeding to the next line of code.

Remember to replace "Balances" with the actual name of your database and adjust the code according to your specific use case.

Have any questions? Let us know on our discord! https://discord.gg/Sa2MjMNkm3