Challenge - 5 Problems
Express Document Creator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this Express route handler?
Consider this Express route that creates a new document in a MongoDB collection using Mongoose. What will the client receive when this route is called successfully?
Express
app.post('/items', async (req, res) => { const item = new Item({ name: req.body.name }); await item.save(); res.status(201).json({ id: item._id, name: item.name }); });
Attempts:
2 left
💡 Hint
Look at what is sent in the response and the status code.
✗ Incorrect
The route creates a new item, saves it, then responds with status 201 and a JSON containing only the id and name fields.
📝 Syntax
intermediate2:00remaining
Which option correctly creates a new document and handles errors in Express?
Identify the correct Express route code that creates a new document and sends a 500 status if saving fails.
Attempts:
2 left
💡 Hint
Look for proper async/await usage and error handling.
✗ Incorrect
Option B uses async/await correctly and catches errors to send a 500 status. Option B does not wait for save to complete. Option B lacks error handling. Option B misses await on save, so errors won't be caught.
🔧 Debug
advanced2:00remaining
Why does this Express route not save the document?
This route is supposed to create and save a new document but the database remains unchanged. What is the cause?
Express
app.post('/posts', (req, res) => { const post = new Post(req.body); post.save(); res.status(201).json({ message: 'Post created' }); });
Attempts:
2 left
💡 Hint
Think about asynchronous operations and their completion.
✗ Incorrect
post.save() returns a promise. Without awaiting it or handling the promise, the save may not finish before sending the response, causing the document not to be saved.
❓ state_output
advanced2:00remaining
What is the value of 'result' after this Express route runs?
Given this code snippet, what will be the value of the variable 'result' after the route is called?
Express
let result = null; app.post('/data', async (req, res) => { const doc = new Data(req.body); result = await doc.save(); res.status(201).json(result); });
Attempts:
2 left
💡 Hint
Consider how async/await updates variables in the same scope.
✗ Incorrect
'result' is assigned the resolved value of doc.save(), which is the saved document object including its _id.
🧠 Conceptual
expert2:00remaining
Which option best describes the role of middleware when creating documents in Express?
When building an Express app that creates documents, what is the primary purpose of middleware functions in the request handling chain?
Attempts:
2 left
💡 Hint
Think about what middleware does before the main route logic.
✗ Incorrect
Middleware functions run before route handlers and are used to process, validate, or transform request data before creating documents.