Back to Blog

Building AI-Powered CRUD APIs with Bun.js, MongoDB, and Express - AI Development Guide

In the world of AI development and intelligent systems, creating robust CRUD (Create, Read, Update, Delete) APIs is fundamental for building AI-powered applications. In this comprehensive guide, we’ll walk you through building an AI-ready CRUD API using Bun.js, MongoDB, and Express. This technology stack is perfect for AI backend development, LLM integrations, and intelligent systems that require high performance and scalability.

Why This Stack for AI Development?

  • Bun.js: Ultra-fast JavaScript runtime perfect for AI inference and real-time AI processing
  • MongoDB: Excellent for storing AI model metadata, vector embeddings, and AI training data
  • Express: Flexible framework for building AI microservices and LLM API endpoints

Prerequisites

Before we dive into building AI-powered APIs, make sure you have the following prerequisites:

  1. Bun.js and npm installed on your machine
  2. MongoDB installed and running locally or at a remote server
  3. Basic knowledge of JavaScript, Express, MongoDB, and AI development concepts
  4. Understanding of API design for AI applications

Setting Up the Project

Let’s start by creating a new project directory and setting up the necessary dependencies.

mkdir bunjs-crud-api
cd bunjs-crud-api
npm init -y
bun add express mongoose

We are using Express for building the API and Mongoose as the ODM (Object Data Modeling) library for MongoDB.

Creating the Bun.js CRUD API

Now that our project is set up, let’s create the main app.js file for our CRUD API. You can use the code you provided as a starting point. Here’s a breakdown of the code:

// Import required libraries and models
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const port = 9000;

// Middleware to parse JSON requests
app.use(express.json());

// Connect to MongoDB
app.listen(port, async () => {
  try {
    const connection = await mongoose.connect(
      "mongodb://localhost:27017/users"
    );
    console.log("Connected to MongoDB");
  } catch (error) {
    console.log("Error connecting to MongoDB:", error);
  }
  console.log(`Example app listening at http://localhost:${port}`);
});

// Define routes for CRUD operations
// Create a new user
app.post("/users", async (req, res) => {
  const { name, email, password } = req.body;
  const user = await User.create({ name, email, password });
  res.send(user);
});

// Retrieve all users
app.get("/users", async (req, res) => {
  const users = await User.find({});
  res.send(users);
});

// Retrieve a specific user by ID
app.get("/users/:id", async (req, res) => {
  const id = req.params.id;
  const user = await User.findById(id);
  res.send(user);
});

// Delete a user by ID
app.delete("/users/:id", async (req, res) => {
  const id = req.params.id;
  const user = await User.findByIdAndDelete(id);
  res.send(user);
});

// Update a user by ID
app.put("/users/:id", async (req, res) => {
  const id = req.params.id;
  const { name, email, password } = req.body;
  const user = await User.findByIdAndUpdate(
    id,
    { name, email, password },
    { new: true }
  );
  res.send(user);
});

// Start the Express server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

In this code, we have done the following:

  1. Imported the required libraries and models.
  2. Set up middleware to parse JSON requests.
  3. Established a connection to the MongoDB database.
  4. Defined routes for each CRUD operation (Create, Read, Update, Delete).
  5. Started the Express server.

Creating the User Model

To use the User model in your code, you’ll need to define it. Create a User.model.js file in the same directory as your app.js and define the model as follows:

const mongoose = require("mongoose");

const userSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
});

const User = mongoose.model("User", userSchema);

module.exports = User;

This code defines a simple User schema with fields for name, email, and password.

Running the API

To run your Bun.js CRUD API, execute the following command in your project directory:

npm run start

Your API should now be running at http://localhost:9000. You can use tools like Postman or curl to test the API endpoints you’ve defined.

Conclusion

In this comprehensive guide, we’ve walked you through the process of creating a robust CRUD API using Bun.js, MongoDB, and Express, specifically designed for AI development and intelligent systems. You’ve learned how to set up the project, define API routes, and interact with a MongoDB database using Mongoose.

This AI-ready API can serve as a foundation for building more complex AI applications that require:

  • User management for AI platforms
  • AI model metadata storage
  • Vector database integration
  • LLM API endpoints
  • AI microservices architecture

The combination of Bun.js’s performance, MongoDB’s flexibility, and Express’s simplicity makes this stack ideal for AI backend development and intelligent application architecture. Happy coding with AI development!