Building a CRUD API with Bun.js, MongoDB, and Express

2023-09-19

In the world of web development, creating a CRUD (Create, Read, Update, Delete) API is a fundamental task. In this blog post, we will walk you through the process of building a CRUD API using Bun.js, MongoDB, and Express. This combination of technologies allows us to create a robust and efficient API for managing user data.

Prerequisites

Before we dive into the code, make sure you have the following prerequisites in place:

  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, and MongoDB.

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 blog post, we've walked you through the process of creating a CRUD API using Bun.js, MongoDB, and Express. You've learned how to set up the project, define the API routes, and interact with a MongoDB database using Mongoose. This API can serve as a foundation for building more complex applications that require user data management. Happy coding!