Sling Academy
Home/Node.js/Understanding Mongoose Model.deleteOne() Method with Examples

Understanding Mongoose Model.deleteOne() Method with Examples

Last updated: December 30, 2023

The Mongoose Model.deleteOne() method is a part of the Mongoose ORM library for MongoDB in Node.js applications. It was added to provide a simple and straightforward way to remove a single document from the collection based on a given condition.

The purpose of Model.deleteOne() is to delete a single document from a MongoDB collection that matches a specified filter. It is designed to ensure that only one document is removed, even if multiple documents match the filter.

Syntax, Parameters, and Return Value

Syntax:

Model.deleteOne(filter, [options], [callback])

Parameters:

  • filter: A plain object representing the filter used to select the document to remove.
  • options (optional): Additional options such as writeConcern.
  • callback (optional): A callback function to execute when the delete operation is complete.

Return Value:

The method returns a promise that resolves with an object containing the deletedCount, which indicates how many documents were deleted.

Code Examples

1. Delete a User by Username

Summary: This example demonstrates how to delete a user with a given username from the ‘users’ collection.

import mongoose from 'mongoose';
const { Schema } = mongoose;

const userSchema = new Schema({ username: String });
const User = mongoose.model('User', userSchema);

async function deleteUserByUsername(username) {
    try {
        const result = await User.deleteOne({ username });
        console.log(result.deletedCount); // Expected output: 1 or 0
    } catch (error) {
        console.error('Error deleting user:', error);
    }
}

deleteUserByUsername('johndoe');

2. Conditional Deletion of a Product

Summary: This example shows how to conditionally delete a product from the ‘products’ collection based on price and stock availability.

import mongoose from 'mongoose';
const { Schema } = mongoose;

const productSchema = new Schema({
    name: String,
    price: Number,
    inStock: Boolean
});
const Product = mongoose.model('Product', productSchema);

async function deleteProductIfPriceIsLowAndOutOfStock(name) {
    try {
        const result = await Product.deleteOne({
            name,
            price: { $lt: 5 },
            inStock: false
        });
        console.log(result.deletedCount); // Outputs the number of documents deleted
    } catch (error) {
        console.error('Error deleting product:', error);
    }
}

deleteProductIfPriceIsLowAndOutOfStock('CheapWidget');

Conclusion

The Model.deleteOne() method is a powerful operation in Mongoose that allows for precise deletion of documents from a collection. Its single-document deletion capability ensures that developers can remove data with precision, while its promise-based interface means it can be cleanly integrated into asynchronous code flows using async or chained with .then() for handling outcomes.

Next Article: How to Implement Pagination in Mongoose

Previous Article: Understanding the Mongoose Model.updateOne() Function in Node.js

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates