Creating documents means making new files or data entries on the server. This helps store information like user details or messages.
Creating documents in Express
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
app.post('/path', (req, res) => { // get data from req.body // save data to database or file res.send('Document created') })
Use
app.post to handle creating new data because POST means sending new info.Access the data sent by the user with
req.body after using middleware like express.json().Examples
Express
app.post('/users', (req, res) => { const user = req.body // pretend to save user res.send(`User ${user.name} created`) })
Express
app.post('/notes', (req, res) => { const note = req.body // save note to database res.status(201).send('Note created') })
Sample Program
This program creates a simple Express server that accepts POST requests to /documents. It expects a JSON body with title and content. If both exist, it saves the document in an array and replies with a success message.
Express
import express from 'express' const app = express() app.use(express.json()) const documents = [] app.post('/documents', (req, res) => { const doc = req.body if (!doc.title || !doc.content) { return res.status(400).send('Missing title or content') } documents.push(doc) res.status(201).send(`Document titled '${doc.title}' created`) }) app.listen(3000, () => { console.log('Server running on http://localhost:3000') })
Important Notes
Always use express.json() middleware to read JSON data sent by clients.
Use status code 201 to clearly say a new resource was created.
Validate the incoming data to avoid saving incomplete documents.
Summary
Use app.post to create new documents or data entries.
Access user data with req.body after enabling JSON parsing.
Send a clear response with status 201 when creation is successful.
Practice
1. Which Express method is used to handle creating new documents via HTTP POST requests?
easy
Solution
Step 1: Understand HTTP methods in Express
Express uses different methods likeget,post,put, anddeleteto handle HTTP requests.Step 2: Identify method for creating new data
Thepostmethod is used to create new documents or data entries.Final Answer:
app.post() -> Option AQuick Check:
Creating documents = app.post() [OK]
Hint: Use app.post() for creating new data entries [OK]
Common Mistakes:
- Using app.get() instead of app.post()
- Confusing app.put() with app.post()
- Using app.delete() for creation
2. Which code snippet correctly enables JSON parsing middleware in Express to access
req.body?easy
Solution
Step 1: Identify middleware for JSON parsing
Express providesexpress.json()middleware to parse JSON request bodies.Step 2: Match correct usage
The correct way isapp.use(express.json());to enable JSON parsing.Final Answer:
app.use(express.json()); -> Option BQuick Check:
JSON parsing middleware = express.json() [OK]
Hint: Use app.use(express.json()) to read JSON body [OK]
Common Mistakes:
- Using express.urlencoded() for JSON data
- Using bodyParser.text() instead of JSON parser
- Forgetting to enable any parser middleware
3. What will be the HTTP status code sent when the following Express route successfully creates a document?
app.post('/items', (req, res) => {
// Assume document creation here
res.status(201).send('Created');
});medium
Solution
Step 1: Understand HTTP status codes for creation
Status code 201 means "Created" and is used when a new resource is successfully created.Step 2: Check the code's status method
The code usesres.status(201), so it sends status 201.Final Answer:
201 -> Option DQuick Check:
Creation success status = 201 [OK]
Hint: Use status 201 for successful creation responses [OK]
Common Mistakes:
- Assuming 200 means creation success
- Using 400 or 500 for successful creation
- Not setting status code explicitly
4. Identify the error in this Express route for creating a document:
app.post('/users', (req, res) => {
const user = req.body;
saveUser(user);
res.send('User created');
});medium
Solution
Step 1: Check access to req.body
Without JSON parsing middleware,req.bodywill be undefined.Step 2: Identify missing middleware
The code does not showapp.use(express.json()), soreq.bodywon't work.Final Answer:
Missing JSON parsing middleware to read req.body -> Option CQuick Check:
Missing express.json() causes req.body undefined [OK]
Hint: Always enable express.json() before accessing req.body [OK]
Common Mistakes:
- Thinking res.send must be res.json
- Using app.get for creation routes
- Assuming saveUser must be async here
5. You want to create an Express route that accepts JSON data to create a new product and respond with the created product including an ID. Which code snippet correctly implements this?
hard
Solution
Step 1: Use correct HTTP method and access JSON body
The route usesapp.postand accessesreq.bodywhich is correct for creating a product.Step 2: Add an ID and respond with status 201 and JSON
Assigningproduct.id = Date.now()simulates creating an ID. Responding withres.status(201).json(product)sends the created product with proper status.Final Answer:
Option A code snippet -> Option AQuick Check:
POST + req.body + status 201 + json response = app.post('/products', (req, res) => { const product = req.body; product.id = Date.now(); res.status(201).json(product); }); [OK]
Hint: Use app.post with req.body and res.status(201).json() [OK]
Common Mistakes:
- Using app.get instead of app.post
- Reading data from req.query instead of req.body
- Not sending status 201 on creation
