Bird
Raised Fist0
Expressframework~10 mins

Updating documents in Express - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Updating documents
Receive HTTP PUT/PATCH request
Extract document ID and update data
Call database update method
Database finds document by ID
Update document
Send success response with updated document
The server receives an update request, finds the document by ID, updates it if found, and sends back the updated document or an error.
Execution Sample
Express
app.patch('/items/:id', async (req, res) => {
  const id = req.params.id;
  const updates = req.body;
  const updatedItem = await Item.findByIdAndUpdate(id, updates, { new: true });
  if (!updatedItem) return res.status(404).send('Not found');
  res.send(updatedItem);
});
This code updates an item by ID with new data and returns the updated item or a 404 error if not found.
Execution Table
StepActionInputDatabase ResultResponse Sent
1Receive PATCH requestid=123, updates={name:'New'}N/AN/A
2Call findByIdAndUpdateid=123, updates={name:'New'}Document found and updatedN/A
3Check if updatedItem existsupdatedItem != nullTrue404 Not Found if false
4Send updated documentupdatedItem with new nameN/A200 OK with updated document
5EndN/AN/ARequest complete
💡 Execution stops after sending the updated document response or 404 error.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
idundefined123123123123
updatesundefined{name:'New'}{name:'New'}{name:'New'}{name:'New'}
updatedItemundefinedundefined{_id:123, name:'New'}{_id:123, name:'New'}{_id:123, name:'New'}
Key Moments - 2 Insights
Why do we check if updatedItem exists after the update call?
Because if the document with the given ID does not exist, findByIdAndUpdate returns null. Checking updatedItem prevents sending a success response for a non-existent document, as shown in step 3 of the execution_table.
What does the { new: true } option do in findByIdAndUpdate?
It tells the database to return the updated document instead of the original. Without it, updatedItem would be the old document before changes, which can confuse the response as seen in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of updatedItem after Step 2?
Anull
B{_id:123, name:'New'}
Cundefined
DAn error object
💡 Hint
Check the 'Database Result' column in Step 2 of the execution_table.
At which step does the server send the 404 Not Found response if the document is missing?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Check if updatedItem exists' action in Step 3 of the execution_table.
If the { new: true } option is removed, what changes in updatedItem after Step 2?
AupdatedItem will be the original document before update
BupdatedItem will be null
CupdatedItem will be undefined
DupdatedItem will contain an error
💡 Hint
Refer to the key_moments explanation about the { new: true } option.
Concept Snapshot
Updating documents in Express:
- Use PATCH or PUT route with document ID
- Extract ID and update data from request
- Call findByIdAndUpdate(id, updates, { new: true })
- Check if document exists (null means not found)
- Send updated document or 404 error
- { new: true } returns updated document, not original
Full Transcript
This visual execution shows how Express updates documents in a database. First, the server receives a PATCH request with an ID and update data. It calls the database method findByIdAndUpdate with the ID, updates, and the option to return the new document. If the document is found, it updates and returns it. If not found, it sends a 404 error. The variable tracker shows how the ID, updates, and updatedItem change step by step. Key moments clarify why checking for null is important and what the { new: true } option does. The quiz tests understanding of these steps and values.

Practice

(1/5)
1. What does the findByIdAndUpdate method do in Express with Mongoose?
easy
A. It updates a document by its ID and returns the updated document.
B. It deletes a document by its ID.
C. It creates a new document with a given ID.
D. It finds a document but does not update it.

Solution

  1. Step 1: Understand the method purpose

    findByIdAndUpdate is used to find a document by its ID and update it with new data.
  2. Step 2: Check the return value

    When used with { new: true }, it returns the updated document, not the old one.
  3. Final Answer:

    It updates a document by its ID and returns the updated document. -> Option A
  4. Quick Check:

    Update document by ID = A [OK]
Hint: Remember: findByIdAndUpdate updates and returns new data [OK]
Common Mistakes:
  • Confusing update with delete operation
  • Expecting it to create a new document
  • Thinking it only finds without updating
2. Which of the following is the correct syntax to update a document by ID and return the updated document in Express with Mongoose?
easy
A. Model.findOneAndUpdate(id, update);
B. Model.updateById(id, update, callback);
C. Model.update(id, update, { returnNew: true });
D. Model.findByIdAndUpdate(id, update, { new: true }, callback);

Solution

  1. Step 1: Identify correct method and parameters

    The correct method is findByIdAndUpdate with parameters: id, update object, options, and callback.
  2. Step 2: Confirm option for returning updated document

    The option { new: true } ensures the updated document is returned.
  3. Final Answer:

    Model.findByIdAndUpdate(id, update, { new: true }, callback); -> Option D
  4. Quick Check:

    Correct syntax includes { new: true } = C [OK]
Hint: Use { new: true } option to get updated document [OK]
Common Mistakes:
  • Using wrong method name like updateById
  • Omitting the { new: true } option
  • Passing incorrect parameters order
3. Given the code snippet:
Model.findByIdAndUpdate('123', { name: 'Alice' }, { new: true }, (err, doc) => {
  if (err) return console.error(err);
  console.log(doc.name);
});

What will be printed if the update is successful?
medium
A. The old name before update
B. Alice
C. undefined
D. An error message

Solution

  1. Step 1: Understand the update and options

    The update changes the name to 'Alice' and { new: true } returns the updated document.
  2. Step 2: Check the console output

    The callback logs doc.name, which will be 'Alice' after update.
  3. Final Answer:

    Alice -> Option B
  4. Quick Check:

    Updated document name logged = B [OK]
Hint: With { new: true }, console logs updated value [OK]
Common Mistakes:
  • Expecting old value instead of updated
  • Not using { new: true } option
  • Misreading callback parameters
4. Identify the error in this code snippet for updating a document:
Model.findByIdAndUpdate('123', { age: 30 }, (err, doc) => {
  if (err) console.log(err);
  else console.log(doc);
});
medium
A. The update object should be a string
B. Using wrong method name, should be updateById
C. Missing the { new: true } option to get updated document
D. Callback function parameters are incorrect

Solution

  1. Step 1: Check method usage

    The method findByIdAndUpdate is correct and callback parameters are valid.
  2. Step 2: Identify missing option

    Without { new: true }, the returned document is the old one, not updated.
  3. Final Answer:

    Missing the { new: true } option to get updated document -> Option C
  4. Quick Check:

    Return updated doc requires { new: true } = D [OK]
Hint: Add { new: true } to get updated document in callback [OK]
Common Mistakes:
  • Assuming updateById is a valid method
  • Expecting updated doc without { new: true }
  • Thinking update object must be string
5. You want to update a user's email only if the new email is not empty and valid. Which approach correctly updates the document safely in Express with Mongoose?
hard
A. Check email validity before calling findByIdAndUpdate, then update with { new: true } option.
B. Call findByIdAndUpdate directly without validation to save time.
C. Use findByIdAndUpdate with an empty update object if email is invalid.
D. Update the document without callback and ignore errors.

Solution

  1. Step 1: Validate input before updating

    Always check if the new email is valid and not empty before updating to avoid bad data.
  2. Step 2: Use findByIdAndUpdate with { new: true }

    Update the document with the valid email and use { new: true } to get the updated document.
  3. Final Answer:

    Check email validity before calling findByIdAndUpdate, then update with { new: true } option. -> Option A
  4. Quick Check:

    Validate input + update with new:true = A [OK]
Hint: Always validate input before updating documents [OK]
Common Mistakes:
  • Skipping validation and risking bad data
  • Updating with empty or invalid data
  • Ignoring errors by not using callbacks