0
0
Expressframework~5 mins

Deleting documents in Express

Choose your learning style9 modes available
Introduction

Deleting documents lets you remove unwanted or outdated data from your database. It keeps your app clean and up to date.

When a user wants to remove their account or data.
When cleaning up old or expired records automatically.
When an admin deletes inappropriate content.
When correcting mistakes by removing wrong entries.
When freeing up space by deleting unused documents.
Syntax
Express
Model.deleteOne(filter, callback)
Model.deleteMany(filter, callback)
Model.findByIdAndDelete(id, callback)

deleteOne removes the first document matching the filter.

deleteMany removes all documents matching the filter.

Examples
Deletes one user with the given email.
Express
User.deleteOne({ email: 'user@example.com' }, (err) => {
  if (err) console.error(err);
  else console.log('User deleted');
});
Deletes all posts that are not published.
Express
Post.deleteMany({ published: false }, (err) => {
  if (err) console.error(err);
  else console.log('All unpublished posts deleted');
});
Deletes a comment by its unique ID and logs the deleted document.
Express
Comment.findByIdAndDelete('64a1f2b3c4d5e6f7a8b9c0d1', (err, doc) => {
  if (err) console.error(err);
  else console.log('Deleted comment:', doc);
});
Sample Program

This Express app connects to MongoDB and defines a route to delete a user by their email. It uses deleteOne to remove the user document. If no user matches, it sends a 404 response. Otherwise, it confirms deletion.

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

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

const userSchema = new mongoose.Schema({
  name: String,
  email: String
});

const User = mongoose.model('User', userSchema);

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myapp');

// Route to delete a user by email
app.delete('/users', async (req, res) => {
  try {
    const result = await User.deleteOne({ email: req.body.email });
    if (result.deletedCount === 0) {
      return res.status(404).send('User not found');
    }
    res.send('User deleted successfully');
  } catch (error) {
    res.status(500).send('Error deleting user');
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always check if the document exists before or after deleting to handle errors gracefully.

Use deleteMany carefully to avoid removing too much data by mistake.

Deleting documents does not undo automatically; consider backups if needed.

Summary

Deleting documents removes unwanted data from your database.

Use deleteOne, deleteMany, or findByIdAndDelete depending on your need.

Handle errors and check results to keep your app stable.