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 aswriteConcern
.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.