How to use addToSet Operator In Mongoose
This operator also adds elements to an array but only if they are not already present in that array.
Example: Below is an example to push item form an array using addToSet Operator.
// app.js
const express = require('express')
const app = express();
const PORT = 8000;
const { State, dbConnection } = require('./server')
dbConnection();
async function inserting(id, cities) {
// Execute the update operation using findOneAndUpdate()
await State.findOneAndUpdate({ _id: '663b6cd51a77d2866e203fb2' },
{ $addToSet: { cities: cities } },
{ new: true });
console.log('Inserted Successfully.')
}
inserting(
'663b6cd51a77d2866e203fb2',
[
"Pune", "Nagpur",
"Thane", "Nashik",
"Aurangabad", "Solapur",
"Kolhapur", "Navi Mumbai",
"Pimpri Chinchwad"
]
)
// 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