Ravindra BagaleCourses & study guides मराठी Track your progress

Chapter 12: Technology Stacks — LAMP, LEMP, MEAN, MERN

AWS Cloud

12.6 Common backend API for MEAN and MERN (Node + Express + MongoDB)

Use a supported Node.js release and MongoDB to run the learner API below. Angular and React can call the same HTTP contract. The exercise uses private processes and does not require a global process manager.

The private Notes API exercise below starts Express and MongoDB in a temporary workspace. Use the returned note ID to check a real create, read, edit and delete. Confirm rejected requests cannot create records, and independently verify the stored values.

For a deployed service, use the supervisor maintained on your platform. Confirm startup and validate the service through its real HTTP and database paths.

Build and runtime can use different environments

Measure frontend build resources before changing host storage or memory settings. A client-rendered app can commonly be built in a separate environment and deployed as its browser assets. Check whether the selected output also needs a frontend server process.

Ravindra Bagale's Tip

Check the effective Node listener and its actual database destination during deployment. Keep database credentials in backend configuration. A running process is only one check. Test the intended note lookup through the same path as the client.

Lab

खालील खाजगी lab मध्ये note तयार करा आणि response मधल्या ID ने तो पुन्हा वाचा. Text बदलल्यावर HTTP response व database मधला निकाल जुळतो का पाहा. शेवटी तोच test note काढून पुन्हा तपासा.

Give the receiving desk and the counter one set of rules for notes

At Mauli Dairy, a truck arrives with milk cartons. The receiving clerk wants to save a note that says “Delivery received.” A person at the counter wants to see the latest notes, but works on a different screen. Later the clerk corrects the note to “Delivery counted.” Both screens should observe the correction without copying data between their codebases. This is a good reason to put the task of creating, reading and changing notes behind one backend service. A service is a running program available to callers through a defined interface.

In the previous architecture lesson you saw two screens read one resource. In this lesson you own the operations that change the resource as well. You will build and explicitly test an Express API backed by a real private MongoDB process. React and Angular can both use these operations because the API contract is HTTP. The interface makes promises about methods, URLs, data and errors. It does not need to contain a shape intended for a particular screen. The callers can decide how to display the same note or how to ask for a correction.

Running the service does not give it users or permissions automatically. The local exercise runs under one account using fabricated notes, and the app listens on a loopback-only port. For a real deployment add user authentication and enforce authorization for each sensitive operation before sharing it with other people. Authentication establishes who the caller is. Authorization decides whether that caller can view, update or delete the requested note. A note ID is a lookup key, so knowing it does not grant permission to change it. The implementation is deliberately small enough that you can understand the data contract before adding those application controls.

Node.js executes the application outside the browser. Express accepts the incoming HTTP messages and chooses a route, which matches a method and a URL path. Mongoose supplies a model for the database documents and methods for interacting with MongoDB. We can write the service in JavaScript, compile a TypeScript service from source, or choose a different runtime altogether later. As long as the externally observable contract holds, its frontend consumers do not need to change on account of the internal technology. The database runs separately and retains the data files after the application process exits.

Write the contract before writing the handlers

Begin with one concept called a resource. In this app that means a particular stored note or the collection of notes exposed by the service. An HTTP method says what the caller asks to do to the resource. The client sends a method such as GET or POST, the path and, where required, an entity body. The body is the data carried in the request or response. The app reads an incoming JSON body only for operations that expect that format. Each response includes a status to describe the result. The media type identifies the encoding so clients can distinguish a JSON representation from an empty success or a generic HTML error response.

RequestExpected successful resultOne important rejection
GET /api/notes200 with a JSON list of up to twenty recently created notesIf storage is unavailable, a controlled 503 rather than an empty list
POST /api/notes201 with the created note and its resource path in the Location headerBlank or unexpected input is 400, an unsupported body type is 415
GET /api/notes/:id200 with one noteA syntactically valid unknown ID is 404
PATCH /api/notes/:id200 with the note after editing its allowed textMalformed ID or unsupported fields are 400
DELETE /api/notes/:id204 with an empty bodyA later read of that same valid ID is 404

Suppose the caller POSTs {"text":" Delivery received "}. The app accepts the one documented property, trims surrounding spaces and requires a usable length. It asks the model to save the text in the notes collection, then builds a response with the generated ID, stored text and timestamps. The caller gets a success status with a body containing “Delivery received.” The Location response header gives the path of the newly created resource. Follow that path in a subsequent GET. It should return the same ID and stored text. Keeping a known observation about persistence is stronger than assuming a success toast in one screen proves a write.

Now suppose the caller mistakenly sends a property named message instead of text. Since the app hasn't agreed to interpret message, it returns its own 400 input error and does not save a note. If a caller sends an actual text field of only spaces, trimming leaves no usable content. If they send malformed JSON, the JSON parser handles that error before the route. The app caps the body size to keep this tiny service's processing bounded. A valid JSON body with a wrong structure and a file too large to accept are different failures. The chosen status helps each client respond appropriately.

When editing, PATCH identifies a note and sends only the supported changed field. The app validates both the ID and content, updates the matching document, then returns the updated record. A successful change should keep the ID and creation time. It can have a newer update time. An invalid ID never runs a lookup. A correctly shaped ID may still name no record and yields a missing-note response. This helps a client distinguish a malformed link from one that became stale after somebody removed the note.

There is also a distinction between a repeatable retrieval and a repeated creation. GET is intended for retrieving a resource. Repeating a POST can create another note if the first request succeeded but the client missed the response. A real app that retries creates needs a deliberate strategy, such as a supported idempotency key with well-defined server handling, rather than blindly sending another POST. If a client retries DELETE after the first delete succeeded, a subsequent absence still means the desired resource is gone. The HTTP responses do not need to be identical to express that same final effect. Here the first delete returns 204 and the second attempt returns 404.

Keep the request shape, database document and public response distinct

A schema describes the fields and types a collection's documents should have from the application's point of view. Mongoose's schema in the lab requires a bounded text field and records timestamps. A model connects that schema to database operations such as create, find and delete. A stored note has an object identifier, the text and timestamps. Mongoose may also use extra internal fields. MongoDB data claimed by a Mongoose model can still be accessed independently by authorized callers under the database's rules. A Mongoose schema does not automatically become a server-enforced validation rule for every other program that writes to the collection.

Validate inputs near the boundary. Express receives bytes from a caller and parses them into a JavaScript value. The code checks that the value is a plain single-field object with a text string and then normalizes it. Mongoose supplies required-field and length validation in the model as an additional application-side check. For a Mongoose query update, explicitly enable the relevant update validation options. Make the update using a server-created $set object and the validated string. Choose a known identifier and update only an allowed field. Do not treat an HTTP client's submitted object as an arbitrary filter or update document.

The model uses MongoDB's generated ObjectId. The API returns it as a 24-character hexadecimal string in an _id response field. This contract deliberately retains the field name expected by the simple chapter note screens. A returned ID is opaque to a client. The client doesn't need to infer a business meaning from it or invent a new value. Read the returned ID from the response and use it to select the newly created resource. The server verifies the ID shape before passing it to a method that expects something convertible to ObjectId.

Existing documents contain creation and update times, both serialized to ISO-format strings in the response. Sending explicitly named fields helps consumers avoid depending on a model-specific internal value. A frontend developer can rely on text and _id regardless of the Mongoose document type in the backend. This pattern lets you add a private field later without unintentionally sending it through the API. Boundary checks should verify both the fields present and the important fields absent. In the lab, a command-line smoke test parses the JSON and an independent privileged database probe reads the real document separately.

Build and start the local write-capable fixture

Run the lab from one Bash shell as an ordinary user. Have a supported Node version compatible with the selected Express and Mongoose versions, npm, MongoDB Community 8.0, curl and Python 3. Use MONGOD_BIN for the path of a portable server executable if it is outside the shell path. This exercise keeps all data in a fresh temporary directory and runs no operating system service as root. The database binds a private Unix socket, and Express binds only to TCP loopback. Use a free high port through NOTES_API_PORT before starting if 18915 is already used. The package versions make the example reproducible. Run the local test with invented notes and leave the package decisions for a real deployment to its owner.

The simplest way to finish the lab is to run every block in order. When a later frontend lesson links back to the API, its setup uses the first two steps. Those steps start the same application against a new empty database. Leave the original shell open while running a frontend rehearsal. The local database in this lab does not need a password because it uses a socket inside a temporary directory restricted to your account. See the MongoDB lesson for the separate authenticated role check. A deployable backend should run with its own scoped credential and enforce who can call write routes.

Step 1. Prepare a fresh database and private package workspace

set -eu
test "$(id -u)" -ne 0
command -v node >/dev/null
command -v npm >/dev/null
command -v curl >/dev/null
command -v python3 >/dev/null
mongo_bin=${MONGOD_BIN:-$(command -v mongod || true)}
test -x "$mongo_bin"
notes_api_port=${NOTES_API_PORT:-18915}
umask 077
notes_lab=$(mktemp -d /tmp/rb-notes-api.XXXXXX)
printf 'Private Notes API lab: %s\n' "$notes_lab"
api_pid=
db_pid=
stop_notes_child() {
  if [ -n "$1" ]; then
    kill -TERM "$1" 2>/dev/null || true
    wait "$1" 2>/dev/null || true
  fi
}
notes_cleanup() {
  stop_notes_child "$api_pid"
  stop_notes_child "$db_pid"
  case "$notes_lab" in
    /tmp/rb-notes-api.??????) rm -rf -- "$notes_lab" ;;
  esac
}
trap notes_cleanup EXIT
mkdir "$notes_lab/data" "$notes_lab/socket"
printf '%s\n' '{"name":"private-dairy-notes","version":"1.0.0","private":true}' \
  > "$notes_lab/package.json"
npm --prefix "$notes_lab" install --ignore-scripts --save-exact express@5.2.1 mongoose@9.12.3
notes_socket="$notes_lab/socket/notes-api.sock"
NOTES_DB_URI=$(node -p '"mongodb://" + encodeURIComponent(process.argv[1]) + "/dairy_notes?directConnection=true"' "$notes_socket")
export NOTES_DB_URI
start_notes_db() {
  "$mongo_bin" --dbpath "$notes_lab/data" --bind_ip "$notes_socket" \
    --unixSocketPrefix "$notes_lab/socket" --filePermissions 0700 \
    --logappend --logpath "$notes_lab/mongod.log" &
  db_pid=$!
  for attempt in $(seq 1 40); do
    if test -S "$notes_socket"; then return 0; fi
    if ! kill -0 "$db_pid" 2>/dev/null; then break; fi
    sleep 0.25
  done
  printf 'MongoDB startup failed. Read %s/mongod.log.\n' "$notes_lab" >&2
  return 1
}
start_notes_db

When the package operation completes, the temporary directory contains project-specific dependencies and their lock file. The listener uses only a socket path under that directory. The URI percent-encodes the path so the driver can identify it as a local socket. The final section in the URI also selects the dairy_notes database for model operations in this lab. Waiting for the socket is an early sign of progress. The API performs a real connection before publishing its startup marker in the next step.

Step 2. Implement the routes and wait for the API to accept connections

cat > "$notes_lab/server.cjs" <<'JS'
const express = require('express');
const mongoose = require('mongoose');

const app = express();
app.disable('x-powered-by');
const noteSchema = new mongoose.Schema({
  text: { type: String, required: true, minlength: 1, maxlength: 200 },
}, { timestamps: true, bufferCommands: false });
const Note = mongoose.model('Note', noteSchema);

function noteBody(note) {
  return {
    _id: note._id.toString(),
    text: note.text,
    createdAt: note.createdAt.toISOString(),
    updatedAt: note.updatedAt.toISOString(),
  };
}

function requireJson(req, res, next) {
  if (!req.is('application/json')) {
    return res.status(415).json({ error: 'expected application/json' });
  }
  return next();
}
const readJson = express.json({ limit: '4kb' });
function textInput(body) {
  if (!body || Array.isArray(body) || typeof body !== 'object') return null;
  if (Object.keys(body).length !== 1 || typeof body.text !== 'string') return null;
  const text = body.text.trim();
  return text.length >= 1 && text.length <= 200 ? text : null;
}

function withStorage(route) {
  return async (req, res, next) => {
    try {
      await route(req, res);
    } catch (error) {
      if (mongoose.connection.readyState !== 1 ||
          ['MongoNetworkError', 'MongoNetworkTimeoutError', 'MongoServerSelectionError'].includes(error.name)) {
        console.error('notes storage unavailable:', error.name);
        return res.status(503).json({ error: 'notes temporarily unavailable' });
      }
      return next(error);
    }
  };
}

app.get('/api/health', (req, res) => res.json({ running: true }));
app.get('/api/ready', withStorage(async (req, res) => {
  await mongoose.connection.db.command({ ping: 1 });
  res.json({ storageResponding: true });
}));
app.param('id', (req, res, next, id) => {
  if (!mongoose.isObjectIdOrHexString(id)) {
    return res.status(400).json({ error: 'invalid note id' });
  }
  return next();
});
app.get('/api/notes', withStorage(async (req, res) => {
  const notes = await Note.find().sort({ createdAt: -1, _id: -1 }).limit(20).lean();
  res.json(notes.map(noteBody));
}));
app.post('/api/notes', requireJson, readJson, withStorage(async (req, res) => {
  const text = textInput(req.body);
  if (text === null) return res.status(400).json({ error: 'expected one nonempty text field of at most 200 characters' });
  const note = await Note.create({ text });
  const result = noteBody(note);
  return res.location('/api/notes/' + result._id).status(201).json(result);
}));
app.get('/api/notes/:id', withStorage(async (req, res) => {
  const note = await Note.findById(req.params.id).lean();
  if (!note) return res.status(404).json({ error: 'unknown note' });
  return res.json(noteBody(note));
}));
app.patch('/api/notes/:id', requireJson, readJson, withStorage(async (req, res) => {
  const text = textInput(req.body);
  if (text === null) return res.status(400).json({ error: 'expected one nonempty text field of at most 200 characters' });
  const note = await Note.findByIdAndUpdate(req.params.id, { $set: { text } }, {
    returnDocument: 'after', runValidators: true,
  }).lean();
  if (!note) return res.status(404).json({ error: 'unknown note' });
  return res.json(noteBody(note));
}));
app.delete('/api/notes/:id', withStorage(async (req, res) => {
  const note = await Note.findByIdAndDelete(req.params.id);
  if (!note) return res.status(404).json({ error: 'unknown note' });
  return res.status(204).end();
}));
app.use((req, res) => res.status(404).json({ error: 'unknown route' }));
app.use((error, req, res, next) => {
  if (res.headersSent) return next(error);
  if (error.type === 'entity.parse.failed') {
    return res.status(400).json({ error: 'malformed JSON' });
  }
  if (error.type === 'entity.too.large') {
    return res.status(413).json({ error: 'request body too large' });
  }
  if (error.type === 'charset.unsupported' || error.type === 'encoding.unsupported') {
    return res.status(415).json({ error: 'unsupported request encoding' });
  }
  console.error('notes handler failed:', error.name);
  return res.status(500).json({ error: 'unexpected API error' });
});

async function main() {
  await mongoose.connect(process.env.NOTES_DB_URI, { serverSelectionTimeoutMS: 1200 });
  const server = app.listen(Number(process.argv[2]), '127.0.0.1', error => {
    if (!error) {
      console.log('Private notes API ready');
      return;
    }
    console.error('notes listener failed:', error.code);
    process.exitCode = 1;
    void mongoose.disconnect();
  });
  process.once('SIGTERM', () => {
    server.close(() => { void mongoose.disconnect(); });
  });
}
main().catch(error => {
  console.error('notes API startup failed:', error.name);
  process.exitCode = 1;
});
JS
node --check "$notes_lab/server.cjs"
node "$notes_lab/server.cjs" "$notes_api_port" >"$notes_lab/api.log" 2>&1 &
api_pid=$!
for attempt in $(seq 1 40); do
  if grep -Fq 'Private notes API ready' "$notes_lab/api.log"; then break; fi
  if ! kill -0 "$api_pid" 2>/dev/null; then break; fi
  sleep 0.25
done
grep -Fq 'Private notes API ready' "$notes_lab/api.log"
notes_url="http://127.0.0.1:$notes_api_port"

Follow the code top to bottom. The model declares the stored fields. The noteBody function chooses the public representation, converting the ID and date types into strings. Middleware is code Express runs when matching requests before a route's main action. Here an input route verifies the media type, uses a capped JSON parser, and checks the data before accessing the model. The parameter validator rejects an invalid route ID early. Storage handlers call Mongoose and turn expected missing-row or transient database outcomes into different responses. The final error handler protects the public response from exposing internal stack information.

The app waits for the initial connection to MongoDB before advertising its HTTP startup marker. If that connection fails, the log has a startup error rather than a successful marker for an unusable demo. During operation the database can still disappear. The health endpoint reports that the API process can answer, the readiness check tests whether the database responds, and real note requests check the selected collection and permissions. One successful ping may not prove that a different production role can insert a note. Use the complete request tests for that claim.

Prove creation, correction, restart persistence and deletion

Step 3. Send exact HTTP requests and check the actual stored data

api_request() {
  local method=$1 endpoint=$2 expected=$3 actual
  shift 3
  actual=$(curl --noproxy '*' --silent --show-error --max-time 8 \
    --request "$method" -o "$notes_lab/body" -D "$notes_lab/headers" \
    -w '%{http_code}' "$@" "$notes_url$endpoint")
  printf '%s %s %s\n' "$actual" "$method" "$endpoint"
  test "$actual" = "$expected"
}
json_type='Content-Type: application/json'
api_request GET /api/health 200
grep -Fq '"running":true' "$notes_lab/body"
api_request GET /api/ready 200
grep -Fq '"storageResponding":true' "$notes_lab/body"
api_request GET /api/notes 200
grep -Fxq '[]' "$notes_lab/body"
api_request POST /api/notes 415 -H 'Content-Type: text/plain' --data 'plain'
api_request POST /api/notes 400 -H "$json_type" --data '{"text":'
grep -Fq 'malformed JSON' "$notes_lab/body"
api_request POST /api/notes 400 -H "$json_type" --data '{"text":"   "}'
api_request POST /api/notes 400 -H "$json_type" --data '{"message":"Not our schema"}'
python3 - >"$notes_lab/too-big.json" <<'PY'
import json
print(json.dumps({"text": "a" * 5000}))
PY
api_request POST /api/notes 413 -H "$json_type" --data-binary "@$notes_lab/too-big.json"
grep -Fq 'request body too large' "$notes_lab/body"
api_request GET /api/notes 200
grep -Fxq '[]' "$notes_lab/body"
api_request POST /api/notes 201 -H "$json_type" --data '{"text":"  Delivery received  "}'
cp "$notes_lab/body" "$notes_lab/created"
note_id=$(python3 - "$notes_lab/created" <<'PY'
from datetime import datetime
import json, re, sys
from pathlib import Path

note = json.loads(Path(sys.argv[1]).read_text())
assert set(note) == {"_id", "text", "createdAt", "updatedAt"}
assert re.fullmatch(r"[0-9a-f]{24}", note["_id"])
assert note["text"] == "Delivery received"
assert datetime.fromisoformat(note["createdAt"].replace("Z", "+00:00")).tzinfo
assert note["createdAt"] == note["updatedAt"]
print(note["_id"])
PY
)
grep -iq "^Location: /api/notes/$note_id" "$notes_lab/headers"
note_path="/api/notes/$note_id"
api_request GET "$note_path" 200
cmp "$notes_lab/body" "$notes_lab/created"
api_request GET /api/notes/bad-id 400
grep -Fq 'invalid note id' "$notes_lab/body"
api_request GET /api/notes/000000000000000000000000 404
grep -Fq 'unknown note' "$notes_lab/body"
api_request PATCH "$note_path" 400 -H "$json_type" --data '{"text":"New","owner":"me"}'
api_request PATCH "$note_path" 200 -H "$json_type" --data '{"text":"Delivery counted"}'
python3 - "$notes_lab/created" "$notes_lab/body" <<'PY'
import json, sys
from pathlib import Path

before, after = [json.loads(Path(p).read_text()) for p in sys.argv[1:]]
assert set(before) == set(after)
assert after["_id"] == before["_id"] and after["createdAt"] == before["createdAt"]
assert after["updatedAt"] >= before["updatedAt"] and after["text"] == "Delivery counted"
PY
cp "$notes_lab/body" "$notes_lab/edited"
api_request GET /api/notes 200
python3 - "$notes_lab/edited" "$notes_lab/body" <<'PY_LIST'
import json, sys
from pathlib import Path

one, many = [json.loads(Path(p).read_text()) for p in sys.argv[1:]]
assert many == [one], many
PY_LIST
cat > "$notes_lab/read-direct.cjs" <<'JS'
const assert = require('node:assert/strict');
const { mongo } = require('mongoose');

async function run() {
  const client = new mongo.MongoClient(process.env.NOTES_DB_URI, { serverSelectionTimeoutMS: 2000 });
  try {
    const notes = client.db('dairy_notes').collection('notes');
    const row = await notes.findOne({ _id: new mongo.ObjectId(process.argv[2]) });
    if (process.argv[3] === 'present') {
      assert.equal(row.text, 'Delivery counted');
      assert.ok(row.createdAt instanceof Date && row.updatedAt instanceof Date);
    } else {
      assert.equal(process.argv[3], 'absent');
      assert.equal(row, null);
    }
    console.log('Independent database result:', process.argv[3]);
  } finally {
    await client.close();
  }
}
run().catch(error => {
  console.error(error.name, error.message);
  process.exitCode = 1;
});
JS
node "$notes_lab/read-direct.cjs" "$note_id" present

The helper saves HTTP status, headers and body separately. It checks failures before creating a note, then confirms the list is still empty. A success marker could not prove that the rejected body stayed out of the database. This control comparison can. The script reads the ID from the actual response and compares the subsequent resource response with the created body. It compares the edited record with the original to see what persisted. Timestamps are represented by strings over HTTP, and the separate database client verifies they are native dates in storage.

The observed response always has the same four expected fields. The public update identifies the resource by its stored key and only changes the accepted text. A deliberately unsupported property fails before the update. The raw MongoDB client opens an independent connection separate from the HTTP server's model functions. It checks the precise object identifier in the database and verifies the stored text. That is useful when deciding if a write succeeded but the interface displayed an old value. The demonstration doesn't simply assume an HTTP status means the desired record was correctly persisted.

Step 4. Distinguish liveness, availability and durable data

stop_notes_child "$db_pid"
db_pid=
api_request GET /api/health 200
api_request GET /api/ready 503
grep -Fq 'notes temporarily unavailable' "$notes_lab/body"
api_request GET "$note_path" 503
grep -Fq 'notes temporarily unavailable' "$notes_lab/body"
grep -Fq 'notes storage unavailable:' "$notes_lab/api.log"
api_request GET /api/notes/bad-id 400
start_notes_db
for attempt in $(seq 1 20); do
  if api_request GET /api/ready 200; then break; fi
  sleep 0.25
done
grep -Fq '"storageResponding":true' "$notes_lab/body"
node "$notes_lab/read-direct.cjs" "$note_id" present
api_request GET "$note_path" 200
cmp "$notes_lab/body" "$notes_lab/edited"

The temporary availability failure is induced by stopping the database without stopping Express. The health path still returns a result from the HTTP application. Readiness and real reads reflect the missing database. The invalid ID check can still answer because it uses the app's own input rules. Once the daemon restarts using the same files, verify the actual record returns with the original ID and edited text. The successful query after restart establishes persistence across this controlled outage. The client settings use a short timeout for this learning fixture. A real service should choose timeouts and retry behavior with its latency budget, error paths and concurrency in mind.

Step 5. Remove the exact test record, then tear down the private fixture

api_request DELETE "$note_path" 204
test ! -s "$notes_lab/body"
api_request GET "$note_path" 404
grep -Fq 'unknown note' "$notes_lab/body"
api_request DELETE "$note_path" 404
node "$notes_lab/read-direct.cjs" "$note_id" absent
api_request GET /api/notes 200
grep -Fxq '[]' "$notes_lab/body"
notes_cleanup
trap - EXIT
test ! -e "$notes_lab"
printf 'Private Notes API fixture removed.\n'

After deleting the selected record, read it through the API and directly to confirm it isn't in storage. The successful 204 body should be empty. A frontend should not call its JSON parser on that successful response. The follow-up 404 describes a different outcome for the second request, while the stored result remains absent. Clean up only the processes and temporary directory created by this run. The code deliberately checks the temporary path pattern before removing files. It neither installs nor unregisters a system service. If a later lesson asks you to reuse the public-shaped loopback API, start a fresh fixture with the first two steps of this lab.

Let callers distinguish input, access, missing data and outage

Imagine the dairy employee says the button “did nothing.” A good backend makes that report easier to investigate. First identify the operation they attempted. The successful status from the list does not establish that the POST body was accepted. Find the request method and route, whether the receiving app parsed it and the error representation it returned. The frontend can then say “Enter a note,” “That note no longer exists,” or “Notes are temporarily unavailable.” Using one generic client catch for all these cases deprives the user and the operator of information each could act on.

Start with the request that has a wrong body type. An application expecting JSON declares that expectation through its route and the client sends a matching Content-Type header. The content type does not force the bytes to be valid JSON. The parser checks that separately. If the caller sends malformed syntax, Express's JSON middleware detects it before creating the note. If the JSON is structurally correct but lacks an accepted value of text, app logic rejects it. The fixture tests all three outcomes and then checks the collection stays empty. An operator can use the status and controlled error body to identify which assumption the caller broke.

The API's maximum request-body size is separate from the maximum accepted note length. A JSON body uses bytes. A JavaScript string measures length in UTF-16 code units, and a user's notion of a visible character can span more than one code unit. The simple 200 limit in the exercise is implemented using JavaScript string length. It decides the bound for the app and model, and the parser separately keeps oversized requests from reaching the model. If your product has language-specific rules or promises a certain number of visible graphemes, design and document that rule explicitly. A multi-byte body can hit the parser cap at a different point than an ASCII-only example.

The malformed note ID tells us about the URL, not the existence of a database row. Express's route includes a parameter, which is the matched part of the URL. The parameter validator sends 400 for a value that can't represent an ObjectId in this app. If the value matches the type but no row exists, the app can return 404. Contrast that with 503 while a dependency is unavailable. When the store is down, the app does not know whether that valid note exists. It answers with an availability result, preserving the meaning of an actual 404. A successful empty list likewise means the query completed and there were no matching notes in the available result set.

Validation and authorization come at different boundaries. A text string can be correctly formed even if the caller is not allowed to create a note. A real receiving clerk may have create and edit permissions, while the counter has read-only access. A private database using only one account with scoped writes won't know which human made a particular HTTP request unless the service carries that identity and enforces it. Plan the app's authentication and authorization at the application boundary and its database permissions at the storage boundary. The app should give each role only the operations it needs. Store human identities separately from short-lived transport details and avoid trusting a caller's choice of an owner field.

For example, if multiple stores use one notes service, a request from a signed-in person at Shop A should not be able to read a note belonging to Shop B simply by knowing its ID. The app needs a verified shop identity and a query restricted to that identity or condition. Depending on its public access policy it might respond with a generic missing result or an explicit forbidden status. Design which distinction is appropriate rather than relying on an implied rule. A test should show a permitted action for the correct shop and an otherwise-valid rejected action from the other shop. The isolated fixture does not handle multi-tenant access. Its deliberately simple filter matches a note in one practice database.

Keep diagnostic errors out of the public contract. The Express error handler sends bounded JSON for expected parser problems and generic JSON for an unexpected exception. The application logs a short class of error privately to distinguish storage from other server issues. In a maintained service, use logs with controlled access, an understandable request ID strategy, and enough context to diagnose errors without recording credentials or customer notes. The public caller can sometimes find the problem from the status and message alone. The operator needs the additional private evidence for problems such as a misconfigured database URI.

Plan what happens when the app has more callers and notes

The example's list caps the results at twenty and sorts by descending creation time with a stable identifier as the tie-breaker. Without a tie-breaker two notes created at the same millisecond can appear in a different order across equivalent reads. The sorted result makes the newest notes visible first for the simple counter screen. The limit prevents returning an ever-growing collection to each visitor. It does not itself make the database query efficient at scale. Without a suitable index the server may still read or sort much more data than it sends. A deployed app should compare query plans and observed workload before choosing an index and introducing a pagination scheme.

Pagination is a way to fetch results in bounded chunks. A future latest-notes API could return a batch plus a cursor that describes where to continue. With the chosen order, the pair of the last document's creation time and ID is an example of the boundary a server would need. Using only the time can skip notes that share a timestamp. Using an offset can show duplicates or miss entries if new notes arrive between page requests unless the API manages that behavior deliberately. Don't tell users the exercise lists every stored document merely because it uses the URL for the collection. Its contract states that the response contains up to twenty recent notes.

Picture two team members opening the same note. They both see “Delivery received.” The first changes it to “Delivery counted.” The second has not reloaded the record and changes it to “Warehouse shelf.” The exercise allows a later valid update to overwrite the previous text. Being able to perform an atomic update on one selected document does not automatically prevent one client from overwriting a later version with its stale edit. A real team may choose to check an expected version in the update filter and return a meaningful conflict or HTTP precondition failure when that version no longer matches. Then the client can retrieve the latest text and decide what to keep.

Write down that race with actual values. If the first editor sends a version of nine and it succeeds, the note becomes version ten. The second editor still carries nine. With an appropriate conditional update, the server recognizes that another edit already changed the resource and the second write does not replace it. The client should show enough information for the user to understand the conflict and submit a new deliberate change. An independent read confirms version ten and the first editor's text during that test. These version numbers illustrate a design extension, not a field implemented in the private fixture. Using only a response timestamp and checking it in the browser would leave the database update race unresolved.

A fresh connection for every request can add work and make dependency behavior harder to control. The application creates a shared Mongoose connection and models use it for requests. Most database drivers use connection pools, which are managed sets of reusable connections. The independent read deliberately creates a different short-lived client to verify actual storage, then closes it. Real services should choose pool limits, timeouts and concurrency with the capacity of the database and the number of running app replicas in mind. A small per-process limit can still be large when multiplied across many hosts. A short local timeout catches dependency failure quickly in this exercise without setting a universal deployment default.

Another real deployment question is where the app executes. In the practice, you open one terminal and start the Node process directly. A real service supervisor can restart the process, configure its runtime environment and capture logs. A supervisor that says “online” has observed process state, so it does not replace the HTTP and data tests. Select the mechanism your platform maintains, such as systemd, PM2 or a container orchestrator. Configure the intended working directory, execution identity, startup and shutdown behavior, and approved secret mechanism. Confirm the backend listens only where authorized clients or the private reverse proxy can reach it.

The operating system sends a SIGTERM signal when the exercise stops an owned child. The API tries to stop accepting new connections and closes its database connection after the HTTP server closes. Upon the next startup it opens a new database connection before declaring readiness. Production shutdown also needs sensible expectations for active requests, long-lived connections and timeouts. Make a short test that starts a known request before a controlled deployment, then checks which requests finished and how the new version accepted traffic. An abrupt process stop doesn't demonstrate a healthy handoff even when the newer instance appears later.

Connect, test and release a second frontend safely

A frontend developer can test creation without having access to the database. On a test machine the page submits one JSON field to the API path. The browser can use a relative URL so the frontend and its reverse proxy share one origin. The development browser may instead use a local dev proxy, or the app may intentionally use a separately hosted API with appropriate CORS configuration. Decide how this environment is supposed to route browser API requests. Check the public request, not just a different private Node URL. Keep database credentials behind the API and do not expose the backend listener publicly just to make a frontend call work.

The frontend handling a create request can check the returned 201 and use the result to display the added note. It can alternatively fetch the newest list after successful creation. Use the resource ID returned by the app, together with its documented path, when building an edit or delete action. If the create fails and sends a structured error, show a useful message without assuming a next GET will include the note. For a delete, confirm success with status 204 and update the list or request it again. Running a JSON parser on the successful empty body would turn the confirmed success into a frontend error.

For example, a React button and an Angular form could both display “Delivery received” after reading the same object. A test changes it to “Delivery counted,” retrieves the generated ID from one response, then asks each interface to show it. Capture what triggers each fetch, the expected status and how the UI changes. An interface that keeps an old value locally after receiving a newer confirmed response has a different defect than an API that never stored the new text. The independent database probe and the captured HTTP response provide two places to check before altering the client code.

Keep one cross-client contract example with your release process. When a new version adds a field, older consumers often continue working if they use only documented required data. Changing a field name or returning a new type can break them. If the backend changes its internal ObjectId serialization or replaces the public _id with key, coordinate changes in both frontends or add a dedicated compatibility layer. A release check that compares real JSON keys and types will catch such a change before someone simply sees a blank button or a missing list item. Testing only that the status was 200 would not cover the contract.

For a cloud-facing release choose an intentional recent stack and app security model. Install supported Node software through documented package or vendor methods appropriate for the platform. Do not assume a server needs a global PM2 installation or disk swap for the backend. Frontend builds and a running backend can have different resources and lifecycles. Build frontend assets separately when that fits the team and chosen deployment method. To understand capacity, measure the expected build workload and runtime usage before modifying disk, memory or operating-system defaults on a shared host.

Keep a repeated creation test available for the day the product asks about automatic retries. Imagine the backend receives a POST, stores “Delivery received,” and prepares the 201. The client's connection drops before it receives that answer. The client cannot tell from its local timeout whether the first operation succeeded. If it sends the same POST again to this example, the database can legitimately contain two different notes with two IDs. A release that promises safe deduplication needs a separate agreement about a request key, how it survives process restarts, and what happens when two callers use that key concurrently. For the exercise, find the first note with the ordinary read paths before experimenting with another create, and remove only the records intentionally created in the fixture.

Conversely, if a caller sees an invalid-input response for a malformed body, it should correct the input rather than retry the same request. An availability response sometimes justifies a limited retry with delay, particularly for a straightforward read. The client needs a bounded retry policy so a temporary database issue does not cause every active screen to amplify the workload. The application owner should document which operations are safe to repeat and what clients should show while waiting. These decisions build on the status semantics you verify in the lab.

When something fails after a release, compare the external API route and a direct private request from an authorized operator session. Start from the same method and body shape, and keep credential differences in mind. A 502 before Express receives the request points to the HTTP proxy boundary. A controlled JSON error with the correct API shape tells you the app itself could respond. A valid body but wrong record value calls for an independent storage check in the intended environment. Save the previous app release and plan compatible database changes so you can recover the working contract. Run an authorized post-rollback lookup that covers the affected behavior and a neighboring unaffected operation.

Use the response contract to explain results in an interview

Interview answers

How can a single API power both MEAN and MERN?

Angular and React implement interfaces. They can both send the same documented HTTP method, path, and body, and read the API's returned JSON fields or status. Express chooses the behavior, Mongoose builds and queries the application model, and MongoDB owns the stored note. The backend does not need to know which screen sent an equivalent request. Authorization should still use the verified caller identity and resource policy.

What is the difference between a syntactically invalid ID and an absent note?

A malformed key such as bad-id fails the application's format check. It gives 400 before querying storage. A 24-character hexadecimal representation can be well-formed and still match no document. When the database query succeeds but finds none, the application sends 404. If the database cannot answer, the app reaches neither conclusion and returns temporary unavailability.

What does the model's schema guarantee in this application?

When the app uses the model, it checks the string rules and provides defined persistence behavior, including timestamps. An update query needs its supported validation options enabled if the server expects those validators to run. A separate database client bypasses these application-level validators. Enforce database-side document validation too if multiple writers must meet the same invariant independently.

How do you prove an edit saved and isn't just a live screen state?

Read the original ID, send the valid correction and assert the response retains the ID with the new text. Read the same stored record through an independent authorized database client. Restart the temporary database and repeat the exact query or API read. A loading message and successful process health check are weaker observations.

Why does the app return 204 before the caller reloads the note list?

The selected delete completed, so the handler can send success without a body. The consumer should use the status, then reconcile its list with the backend as needed. A later GET of the same key returns a missing-note result. An independent lookup can verify that the document was actually removed.

Quick quiz

The notes list returns 503 while the health endpoint returns 200. What should the screen show?

A temporary error for the requested data. The Node process is alive but the list did not complete. Showing an empty list as if the app received zero records would confuse an unavailable storage operation with a successful query.

What should the API do when a valid PATCH carries a text field plus an unsupported owner field?

Reject the request with the documented input failure. The exercise accepts exactly one field. It selects update fields server-side instead of interpreting whatever the browser sends. The note should still have its previous value after the rejected request.

After two clients edit from an older copy, does this simple app reject the second update automatically?

No. The server validates the ID and text, then allows an update to the selected document. A conflict check would require a specific expected version and an atomic update condition. The app's timestamps and correctly typed request alone don't express that policy.

Practice tasks

  1. In the private fixture, create another short note and record its Location header. Use that path to retrieve it, and independently check the returned key and text. Clean up the created test note without touching notes outside your fixture.
  2. Send a syntactically valid unknown ID twice, once with the database running and once during the controlled dependency pause. Predict the change from known absence to temporary unavailability and compare the health response at the same two times.
  3. Design a test for a future role system with an authorized writer and a counter reader. Use the same well-formed edit body for both. Identify the expected role-dependent response and a follow-up direct read confirming only the allowed operation changed the note.

Post, then use the returned path

Check 201 and the resource ID in the response. Follow its Location to prove the note can be read.

Model and contract are separate

Validate request values, maintain storage types and project a deliberate public response shape.

Unavailable does not mean empty

A 503 is a failed dependency-backed operation. A successful empty list means the selected query ran and returned no notes.

Prove a delete by reading again

A 204 contains no body. A later 404 and independent absent row verify the effect.

Official references