An API with Node.js and Express

TeselaDB

TeselaDB

TeselaDB team

25 minBeginner

Build an orders API with Express and the official MongoDB driver that saves and reads in TeselaDB.

A Node.js API uses TeselaDB with the official MongoDB driver, the same way it would use MongoDB. Here you write with Express an orders API with one endpoint to create an order and another to read it.

What you will build

An Express server on port 3000 with POST /orders, which validates the order and saves it, and GET /orders/:id, which returns it or answers 404.

Requirements

  • Node.js 18 or later.
  • A TeselaDB cluster and a user with readWrite on the shop database.
  • The connection string with TLS in the TESELADB_URI environment variable, as in Node.js.

1. Create the project

Shell
mkdir orders-api && cd orders-api
npm init -y
npm install express mongodb

2. Write the API

Save it as app.mjs. The client is created once at start-up and shares its connections across every request:

JavaScript
import express from "express";
import { MongoClient, ObjectId } from "mongodb";

const client = new MongoClient(process.env.TESELADB_URI);
const orders = client.db("shop").collection("orders");
const app = express();
app.use(express.json());

app.post("/orders", async (req, res) => {
  const { customer, total } = req.body;
  if (typeof customer !== "string" || typeof total !== "number" || total < 0) {
    return res.status(400).json({ error: "customer and a total of 0 or more are required" });
  }
  const { insertedId } = await orders.insertOne({ customer, total, createdAt: new Date() });
  res.status(201).json({ id: insertedId });
});

app.get("/orders/:id", async (req, res) => {
  if (!ObjectId.isValid(req.params.id)) return res.status(404).end();
  const order = await orders.findOne({ _id: new ObjectId(req.params.id) });
  if (!order) return res.status(404).end();
  res.json(order);
});

await client.connect();
app.listen(3000, () => console.log("listening on 3000"));

Try it

Start the server with node app.mjs. Then, in another terminal, create an order for Ana with a total of 30 and read it back with the id that the first request returns, which goes in place of <id> in the second command:

Shell
curl -s -X POST localhost:3000/orders -H "content-type: application/json" -d '{"customer":"Ana","total":30}'
curl -s localhost:3000/orders/<id>

The first command returns {"id":"…"} and the second, the order with its creation date. An order without total answers 400.

Clean up

Stop the server with Ctrl+C and delete the test orders from mongosh:

JavaScript
db.getSiblingDB("shop").orders.deleteMany({ customer: "Ana" });

Next steps