Skip to main content

Database

The Database module manages the MongoDB connection and provides helper methods for common database operations.

Usage

import { FluxKit } from "@fluxkitdev/core";

const app = new FluxKit({
database: {
uri: "mongodb://localhost:27017/myapp",
dbName: "myapp", // optional, defaults to URI database
},
});

await app.start({ port: 3000 });

// Access the MongoDB database instance
const db = app.db;

// Use standard MongoDB driver methods
const users = await db.collection("users").find({}).toArray();

API Reference

app.db: Db

The MongoDB Db instance from the official Node.js driver. You can use all standard MongoDB methods.

// Insert a document
await app.db.collection("items").insertOne({
name: "Widget",
price: 9.99,
createdAt: new Date(),
});

// Find documents
const items = await app.db
.collection("items")
.find({ price: { $lte: 20 } })
.sort({ createdAt: -1 })
.toArray();

// Update a document
await app.db.collection("items").updateOne(
{ _id: itemId },
{ $set: { price: 14.99 } }
);

// Delete a document
await app.db.collection("items").deleteOne({ _id: itemId });

app.database.healthCheck(): Promise<boolean>

Checks if the database connection is alive.

const healthy = await app.database.healthCheck();
// => true

app.database.disconnect(): Promise<void>

Gracefully closes the database connection.

process.on("SIGTERM", async () => {
await app.database.disconnect();
process.exit(0);
});

Indexes

You can define indexes for your collections during initialization:

const app = new FluxKit({
database: {
uri: process.env.MONGODB_URI,
indexes: {
users: [
{ key: { email: 1 }, unique: true },
{ key: { createdAt: -1 } },
],
items: [
{ key: { name: "text" } }, // text search index
],
},
},
});

Transactions

MongoDB transactions are supported for multi-document operations:

const session = app.db.client.startSession();

try {
await session.withTransaction(async () => {
await app.db.collection("accounts").updateOne(
{ _id: fromId },
{ $inc: { balance: -amount } },
{ session }
);
await app.db.collection("accounts").updateOne(
{ _id: toId },
{ $inc: { balance: amount } },
{ session }
);
});
} finally {
await session.endSession();
}

Configuration

VariableDefaultDescription
MONGODB_URI--MongoDB connection string (required)
MONGODB_DB_NAMEfrom URIDatabase name override
MONGODB_MAX_POOL10Maximum connection pool size