How to use findByIdAndUpdate In Mongoose
It involves finding a document by its _id and using Mongoose’s update operators to modify the array within that document.
Example: Below is an example to push item using findByIdAndUpdate.
// app.js
const express = require('express')
const app = express();
const PORT = 8000;
const { State, dbConnection } = require('./server')
dbConnection();
// Find the document you want to update
async function inserting(id, cities) {
// Execute the update operation using findByIdAndUpdate()
await State.findByIdAndUpdate(
id,
// Use $push operator to add the new element to the array
{ $push: { cities } },
// Set { new: true } to return the modified document
{ new: true }
);
console.log('Item inserted successfully.')
}
inserting(
'663b75997bcde4bfbf137cc8',
[
"Lucknow", "Kanpur",
"Ghaziabad", "Agra",
"Varanasi", "Meerut",
"Allahabad", "Bareilly",
"Noida", "Saharanpur"
]
)
// server listening
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`)
})
Output:
How to Push Item From an Array in Mongoose ?
In Mongoose, pushing an item to an array can be done using different approaches. To push an item into an array, you can use the $push
operator along with the updateOne()
or updateMany()
method.
We will discuss the different methods to push items from an array in Mongoose:
Table of Content
- Inserting a new document
- Using $push Operator
- Using addToSet Operator
- Using findById
- Using findByIdAndUpdate