Bird
Raised Fist0
Expressframework~5 mins

Updating documents in Express

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
Introduction

Updating documents lets you change saved data in your app. It helps keep information fresh and correct.

When a user edits their profile information on a website.
When an admin changes the status of an order in an online store.
When you want to fix a typo or update details in a saved record.
When syncing data from another source and need to refresh stored info.
Syntax
Express
app.put('/items/:id', async (req, res) => {
  const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
  res.send(updatedItem);
});

Use PUT or PATCH HTTP methods to update data.

findByIdAndUpdate updates the document by its ID and returns the new version with { new: true }.

Examples
Updates only the email field of a user by ID.
Express
app.patch('/users/:id', async (req, res) => {
  const user = await User.findByIdAndUpdate(req.params.id, { email: req.body.email }, { new: true });
  res.json(user);
});
Updates the post document with data from the request body.
Express
app.put('/posts/:id', async (req, res) => {
  const post = await Post.findByIdAndUpdate(req.params.id, req.body, { new: true });
  res.json(post);
});
Sample Program

This Express app connects to a MongoDB database. It defines an Item model with name and price. The PUT /items/:id route updates an item by its ID using data from the request body. It returns the updated item or an error if not found.

Express
import express from 'express';
import mongoose from 'mongoose';

const app = express();
app.use(express.json());

const itemSchema = new mongoose.Schema({
  name: String,
  price: Number
});
const Item = mongoose.model('Item', itemSchema);

app.put('/items/:id', async (req, res) => {
  try {
    const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!updatedItem) return res.status(404).send('Item not found');
    res.json(updatedItem);
  } catch (error) {
    res.status(400).send(error.message);
  }
});

// Connect to MongoDB and start server
mongoose.connect('mongodb://localhost:27017/shop').then(() => {
  app.listen(3000, () => console.log('Server running on port 3000'));
});
OutputSuccess
Important Notes

Always validate and sanitize input data before updating to avoid errors or security issues.

Use { new: true } option to get the updated document back after update.

Handle cases where the document to update does not exist to avoid confusion.

Summary

Updating documents changes saved data to keep it current.

Use findByIdAndUpdate with { new: true } to update and get the new data.

Validate input and handle errors for a smooth user experience.

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