Open In App

How to Push Item From an Array in Mongoose?

Last Updated : 30 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose, an Object Data Modeling (ODM) library for Node.js and MongoDB, makes database interactions easier through a comprehensive API. One of the most frequent operations that developers execute using Mongoose is adding an item to an array of a document. In this article, we will discuss the different ways to push items to an array in Mongoose so that your data manipulation is efficient and effective

What is Mongoose and Why Use it?

Mongoose is an ODM (Object Data Modeling) library for MongoDB. It offers a robust API to drive MongoDB, and it includes data validation tools, schema definitions, querying capabilities, and more. One of the most used data types in MongoDB documents is an array. In Mongoose, pushing an element into an array can be achieved in various ways. To insert an item into an array, you can utilize the $push operator with the updateOne() or updateMany() method.

 In MongoDB, the $push operator can be used to insert an item into an array field in a document. With Mongoose, you can use $push in the updateOne(), updateMany(), or findByIdAndUpdate() functions to insert items into an array field. Still, there are other methods and operators to manage array data effectively, such as $addToSet and findById().

We will discuss the different methods to push items from an array in Mongoose, along with practical examples.

Steps to Set Up a Mongoose Application

Step 1: Create a Node.js Project

first start by creating a new project directory and navigating using the following command

mkdir mongodb-example
cd mongodb-example

Step 2: Install the required modules

Use the following command to install Mongoose and Express:

npm install express  mongoose  

Project Structure:

project-structure
Project Structure

The Updated dependencies in your package.json file is:

 "dependencies": {
"express": "^4.19.2",
"mongoose": "^8.3.4"
}

Example 1: Inserting a New Document with Array Data

The first example demonstrates how to create a new document in MongoDB with an array field and insert data into it. Specifically, we will create a State document where the cities field will be an array of city names.

// 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

Insert Data into the State Collection

In the following code, we will create and insert a new State document with an array of city names.

// 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:

output-1

Example 2: Using $push Operator to Add Items to an Array

In MongoDB, the $push operator is used to append an element to an array within a document. While $push simply adds an item to the array, The $addToSet method ensures that duplicates are avoided. This is useful only when you want unique values in the array.

// 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:

output-3
Output

Example 3: Using addToSet to Ensure Unique Items in Array

While $push simply adds an item to the array. The $addToSet method is used to avoid duplicate items in an array. This is useful when we only want unique values in the array. Below is an example to push item form an array using addToSet Operator.

const express = require('express');
const app = express();
const PORT = 8000;
const { State, dbConnection } = require('./server');

// Establish database connection
dbConnection();

// Function to update the cities field of a document
async function inserting(id, cities) {
try {
// Execute the update operation using findOneAndUpdate()
await State.findOneAndUpdate(
{ _id: id },
// Use $each to handle multiple values
{ $addToSet: { cities: { $each: cities } } },
{ new: true }
);
console.log('Inserted Successfully.');
} catch (error) {
console.error('Error inserting cities:', error);
}
}

// Call the function to insert cities
inserting(
'663b6cd51a77d2866e203fb2',
[
"Pune", "Nagpur",
"Thane", "Nashik",
"Aurangabad", "Solapur",
"Kolhapur", "Navi Mumbai",
"Pimpri Chinchwad"
]
);

// Start the server
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`);
});

Output:

output-4
Output

Example 4: Using findById() to Push Items Manually

This method is used to retrieve document from the collection and once document is founded, we can update it using manual method. 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

output-2-(1)
Output

Example 5: Using findByIdAndUpdate() to Push Items

It involves finding a document by its _id and using Mongoose's update operators to modify the array within that document. This example uses findByIdAndUpdate() to push cities into an array using the $push operator.

// 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(
'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:

output-4
Output

Conclusion

In this article, we've covered various methods for pushing items to an array in Mongoose. Whether using $push, $addToSet, or manual array manipulation, Mongoose provides flexible options for updating array fields in MongoDB documents. These methods are essential for efficiently managing data in your applications, particularly when working with large datasets. By using these approaches, developers can streamline data manipulation while ensuring that their MongoDB collections remain consistent and performance.


Next Article

Similar Reads