MongoDB Support
BlazeKit can automatically generate a full MongoDB controller for your models. This controller includes connection setup and all basic CRUD operations — ready to use out of the box!
What BlazeKit Generates
For each model, BlazeKit creates a MongoDB controller with:
- MongoDB Client Setup — A ready-to-use connection to your database.
- CRUD Functions — Create, Read, Update, and Delete operations for the model.
Example Output
Suppose you have a model User
:
schema.blaze
model User {
name: string
email: string
age: number
}
BlazeKit will generate the following MongoDB controller:
controllers/user.ts
// MongoDB Setup (auto-generated)
import { MongoClient, ObjectId } from "mongodb";
import { User } from "../types";
const uri = process.env.MONGO_URI || "mongodb://localhost:27017";
const databaseName = "your_database_name";
const client = new MongoClient(uri);
async function getCollection() {
if (!client.isConnected?.()) await client.connect();
return client.db(databaseName).collection("users");
}
// CRUD Operations for User
export async function createUser(data: User) {
const collection = await getCollection();
const result = await collection.insertOne(data);
return result.ops?.[0] ?? data;
}
export async function getAllUsers() {
const collection = await getCollection();
return collection.find({}).toArray();
}
export async function getUserById(id: string) {
const collection = await getCollection();
return collection.findOne({ _id: new ObjectId(id) });
}
export async function updateUser(id: string, data: Partial<User>) {
const collection = await getCollection();
await collection.updateOne({ _id: new ObjectId(id) }, { $set: data });
return getUserById(id);
}
export async function deleteUser(id: string) {
const collection = await getCollection();
return collection.deleteOne({ _id: new ObjectId(id) });
}
Notes
- The MongoDB URI is read from
process.env.MONGO_URI
. If not available, it defaults tomongodb://localhost:27017
. - Each model’s collection name is the model name in lowercase with an "s" added (e.g.,
User
→users
).