Updating documents lets you change saved data in your app. It helps keep information fresh and correct.
Updating documents in Express
Start learning this pattern below
Jump into concepts and practice - no test required
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 }.
app.patch('/users/:id', async (req, res) => { const user = await User.findByIdAndUpdate(req.params.id, { email: req.body.email }, { new: true }); res.json(user); });
app.put('/posts/:id', async (req, res) => { const post = await Post.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.json(post); });
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.
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')); });
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.
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
findByIdAndUpdate method do in Express with Mongoose?Solution
Step 1: Understand the method purpose
findByIdAndUpdateis used to find a document by its ID and update it with new data.Step 2: Check the return value
When used with{ new: true }, it returns the updated document, not the old one.Final Answer:
It updates a document by its ID and returns the updated document. -> Option AQuick Check:
Update document by ID = A [OK]
- Confusing update with delete operation
- Expecting it to create a new document
- Thinking it only finds without updating
Solution
Step 1: Identify correct method and parameters
The correct method isfindByIdAndUpdatewith parameters: id, update object, options, and callback.Step 2: Confirm option for returning updated document
The option{ new: true }ensures the updated document is returned.Final Answer:
Model.findByIdAndUpdate(id, update, { new: true }, callback); -> Option DQuick Check:
Correct syntax includes { new: true } = C [OK]
- Using wrong method name like updateById
- Omitting the { new: true } option
- Passing incorrect parameters order
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?
Solution
Step 1: Understand the update and options
The update changes the name to 'Alice' and{ new: true }returns the updated document.Step 2: Check the console output
The callback logsdoc.name, which will be 'Alice' after update.Final Answer:
Alice -> Option BQuick Check:
Updated document name logged = B [OK]
- Expecting old value instead of updated
- Not using { new: true } option
- Misreading callback parameters
Model.findByIdAndUpdate('123', { age: 30 }, (err, doc) => {
if (err) console.log(err);
else console.log(doc);
});Solution
Step 1: Check method usage
The methodfindByIdAndUpdateis correct and callback parameters are valid.Step 2: Identify missing option
Without{ new: true }, the returned document is the old one, not updated.Final Answer:
Missing the { new: true } option to get updated document -> Option CQuick Check:
Return updated doc requires { new: true } = D [OK]
- Assuming updateById is a valid method
- Expecting updated doc without { new: true }
- Thinking update object must be string
Solution
Step 1: Validate input before updating
Always check if the new email is valid and not empty before updating to avoid bad data.Step 2: Use findByIdAndUpdate with { new: true }
Update the document with the valid email and use{ new: true }to get the updated document.Final Answer:
Check email validity before calling findByIdAndUpdate, then update with { new: true } option. -> Option AQuick Check:
Validate input + update with new:true = A [OK]
- Skipping validation and risking bad data
- Updating with empty or invalid data
- Ignoring errors by not using callbacks
