How to use the $pop Operator In Mongoose
The $pop operator removes the first(-1) or last (1 ) element from an array.
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 ) {
const result = await Product.findByIdAndUpdate(productId,
{ reviews: { $pop: { reviewer: -1 } } });
console.log('Review by reviewer removed:', result);
}
pulling('664491772960d488ab55a620' )
// 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