How to use Custom Logic In Mongoose
It involves manually retrieving the document, modifying the array using JavaScript, and then saving the modified document to the database.
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, elementToRemove) {
const product = await Product.findById(productId);
product.reviews = product.reviews.filter(item => item.reviewer !== elementToRemove);
await product.save();
console.log('Review by reviewer removed:', product);
}
pulling('66449c28c1c05b5eccf8071a', 'jatin')
// 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