Bird
Raised Fist0
Expressframework~20 mins

Updating documents in Express - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Express Update Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Express route when updating a document?
Consider this Express route that updates a user document by ID. What will the response be if the user exists and the update is successful?
Express
app.put('/users/:id', async (req, res) => {
  try {
    const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!updatedUser) {
      return res.status(404).send('User not found');
    }
    res.json(updatedUser);
  } catch (error) {
    res.status(500).send('Server error');
  }
});
AResponds with the updated user document in JSON format.
BResponds with a 404 status and 'User not found' message regardless of user existence.
CResponds with a 500 status and 'Server error' message on successful update.
DResponds with the original user document before update.
Attempts:
2 left
💡 Hint
Look at the option { new: true } in findByIdAndUpdate.
📝 Syntax
intermediate
2:00remaining
Which option correctly updates a document using Mongoose in Express?
You want to update a document by ID and return the updated document. Which code snippet is correct?
AUser.update(id, update, { new: true });
BUser.findByIdAndUpdate(id, update, { new: true }, callback);
CUser.updateOne(id, update, { returnNew: true });
DUser.findByIdAndUpdate(id, update); res.send(updatedUser);
Attempts:
2 left
💡 Hint
Check the Mongoose method names and options for returning updated documents.
🔧 Debug
advanced
2:00remaining
Why does this Express update route always return the original document instead of the updated one?
Look at this code snippet. Why does it return the original document before update instead of the updated one?
Express
app.put('/items/:id', async (req, res) => {
  const item = await Item.findByIdAndUpdate(req.params.id, req.body);
  res.json(item);
});
ABecause res.json cannot send updated documents.
BBecause the update data in req.body is ignored by findByIdAndUpdate.
CBecause the route method should be POST, not PUT.
DBecause findByIdAndUpdate defaults to returning the original document unless { new: true } is set.
Attempts:
2 left
💡 Hint
Check the options passed to findByIdAndUpdate.
state_output
advanced
2:00remaining
What is the value of 'result.modifiedCount' after this update operation?
Given this Mongoose update operation, what will be the value of result.modifiedCount if one document was updated successfully?
Express
const result = await User.updateOne({ _id: userId }, { $set: { name: 'Alice' } });
// What is result.modifiedCount?
A1
B0
Cundefined
DThrows an error
Attempts:
2 left
💡 Hint
Check the Mongoose updateOne result object properties.
🧠 Conceptual
expert
3:00remaining
Which option best explains why using findOneAndUpdate with { runValidators: true } is important?
Why should you include { runValidators: true } when updating documents with findOneAndUpdate in Mongoose?
AIt automatically creates a new document if none matches the query.
BIt returns the original document instead of the updated one.
CIt ensures the update respects schema validation rules before saving changes.
DIt disables all validation to speed up the update process.
Attempts:
2 left
💡 Hint
Think about data integrity and schema rules during updates.

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