Bird
Raised Fist0
Expressframework~10 mins

Updating documents in Express - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to update a document by its ID using Express and Mongoose.

Express
app.put('/items/:id', async (req, res) => {
  try {
    const updatedItem = await Item.findByIdAndUpdate(req.params.id, [1], { new: true });
    res.json(updatedItem);
  } catch (error) {
    res.status(500).send(error.message);
  }
});
Drag options to blanks, or click blank then click option'
Areq.params
Breq.headers
Creq.query
Dreq.body
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.params instead of req.body for update data
Forgetting to set { new: true } to return the updated document
2fill in blank
medium

Complete the code to update a document and handle the case when the document is not found.

Express
app.put('/users/:id', async (req, res) => {
  try {
    const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!user) {
      return res.status([1]).send('User not found');
    }
    res.json(user);
  } catch (error) {
    res.status(500).send(error.message);
  }
});
Drag options to blanks, or click blank then click option'
A500
B400
C404
D200
Attempts:
3 left
💡 Hint
Common Mistakes
Using 400 or 500 status codes instead of 404 for not found
Not returning after sending the 404 response
3fill in blank
hard

Fix the error in the code to update a document using Mongoose's updateOne method.

Express
app.patch('/posts/:id', async (req, res) => {
  try {
    const result = await Post.updateOne({ _id: [1] }, req.body);
    res.json(result);
  } catch (error) {
    res.status(500).send(error.message);
  }
});
Drag options to blanks, or click blank then click option'
Areq.body.id
Breq.params.id
Creq.query.id
Dreq.params.postId
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.body.id which may not exist
Using a wrong parameter name like req.params.postId
4fill in blank
hard

Fill both blanks to update a document and return the updated document using findOneAndUpdate.

Express
app.put('/products/:id', async (req, res) => {
  try {
    const product = await Product.findOneAndUpdate({ _id: [1] }, [2], { new: true });
    if (!product) {
      return res.status(404).send('Product not found');
    }
    res.json(product);
  } catch (error) {
    res.status(500).send(error.message);
  }
});
Drag options to blanks, or click blank then click option'
Areq.params.id
Breq.body
Creq.query
Dreq.params.productId
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.query instead of req.body for update data
Using wrong parameter name for ID
5fill in blank
hard

Fill all three blanks to update a document with validation and return the updated document.

Express
app.patch('/orders/:id', async (req, res) => {
  try {
    const order = await Order.findByIdAndUpdate([1], [2], { new: true, runValidators: [3] });
    if (!order) {
      return res.status(404).send('Order not found');
    }
    res.json(order);
  } catch (error) {
    res.status(400).send(error.message);
  }
});
Drag options to blanks, or click blank then click option'
Areq.params.id
Breq.body
Ctrue
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Not enabling runValidators, so invalid data can be saved
Using wrong parameter names for ID or update data

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