0
0
Expressframework~5 mins

Updating documents in Express

Choose your learning style9 modes available
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.