Updating documents lets you change saved data in your app. It helps keep information fresh and correct.
Updating documents in 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 }.
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.