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
Steps to Create an Application
Step 1: Make a folder named ‘mongodb-example’ and navigate to it using this command.
mkdir mongodb-example
cd mongodb-example
Step 2: Install the required modules.
npm install express mongoose
Project Structure:
The Updated dependencies in your package.json file is:
"dependencies": {
"express": "^4.19.2",
"mongoose": "^8.3.4"
}
Example
This code is of server.js file which is same for all approaches example code.
// server.js
const mongoose = require('mongoose')
const DB_URI = 'XXX-XXX'
function dbConnection() {
mongoose.connect(DB_URI)
console.log('Database connected successfully.')
}
const stateSchema = new mongoose.Schema({
name: String,
cities: []
})
const State = mongoose.model('Item', stateSchema)
module.exports = {
dbConnection,
State
}F
Inserting a new document
Items of array can be inserted at when defining new MongoDB document. In this code example array of cities names is inserted document of State collection in the database.
Example: Below is an example of inserting a new document.
// 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(state) {
const newState = new State({
name: state.name,
cities: state.cities // cities in the array form
});
// Save the new item document to the database
await newState.save();
console.log('Inserting Successfully', newState)
}
inserting(
{
name: 'Harayan',
cities: [
"Faridabad", "Gurugram",
"Panipat", "Ambala",
"Yamunanagar", "Rohtak",
"Hisar", "Karnal",
"Sonipat", "Panchkula"
]
}
)
// server listening
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`)
})
Output:
Using $push Operator
In MongoDB, the $push operator is used to append an element to an array within a document.
Example: Below is an example to push item using $push operator.
// app.js
const express = require('express')
const app = express();
const PORT = 8000;
const { State, dbConnection } = require('./server')
dbConnection();
// Find the document and update
async function inserting(id, city) {
await State.updateOne({ _id: id }, { $push: { cities: city } });
console.log('Inserted Successfully.')
}
inserting(
'663b6cd51a77d2866e203fb2',
'Mumbai'
)
// server listening
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`)
})
Output:
Using addToSet Operator
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:
Using findById
This method is used to retrieve document from the collection and once document is founded, we can update it using manual method.
Example: Below is an example to push item using findById.
// 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) {
let state = await State.findById(id);
// Push the city name
for (let i = 0; i < cities.length; i++) {
state.cities.push(cities[i]);
}
// Save the updated document
await state.save()
console.log('Inserted Successfully.')
}
inserting(
'663b5c6b94b144ab32bb8039',
[
"Sirsa", "Jhajjar",
"Kaithal", "Rewari",
"Sirmaur", "Thanesar",
"Pehowa", "Hansi",
"Manduhal"
]
)
// server listening
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`)
})
Output
Using findByIdAndUpdate
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:
Contact Us