How to use $pull Operator In Mongoose
To remove a specific value from an array, employ the $pull operator with the targeted ( to be removed ) value.
Example:
// Filename - app.js
const express = require('express')
const app = express();
const PORT = 8000;
const { Product, dbConnection } = require('./server')
dbConnection(); // connecting to database
async function pulling(productId, categoryToRemove) {
const result = await Product.updateOne(
{ _id: productId },
{ $pull: { categories: categoryToRemove } });
console.log('Category removed:', result);
}
pulling('664491772960d488ab55a620', 'Electronics')
// server listening
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`)
})
Output:
How to Pull Item from an Array in Mongoose ?
In Mongoose, pulling an item from an array can be done using several methods. To pull an item from an array, you can use the $pull operator along with the updateOne() or updateMany() method.
We will discuss the different methods to pull items from an array in Mongoose
Table of Content
- Using $pull Operator
- Pull Based on a Condition
- Pull from Nested Arrays
- Using the $pop Operator
Contact Us