How to Push Item From an Array in Mongoose?
Last Updated :
12 Sep, 2024
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:
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:
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.
JavaScript
// 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.
JavaScript
// 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.
JavaScript
// 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 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.
JavaScript
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:
OutputUsing 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.
JavaScript
// 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 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.
JavaScript
// 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
Similar Reads
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 Op
5 min read
How to Update the First Object in an Array in MongoDB
MongoDB, a popular NoSQL database, offers powerful features for handling complex data structures. One common scenario is updating specific elements within arrays stored in documents. In this guide, we'll focus on updating the first object in an array within a MongoDB document. We'll cover the concep
3 min read
How to Define Schema and Model in Mongoose?
Mongoose is a widely used Object Data Modeling (ODM) library designed for MongoDB in Node.js applications It provides a straightforward way for interacting with MongoDB by offering a schema-based structure. In this article article, we will go through the process of defining schemas and models in Mon
6 min read
How to Update Objects in a Document's Array in MongoDB?
In the area of MongoDB, managing a database with a large collection of documents can be challenging especially when it comes to updating specific objects within arrays of nested objects. This scenario is common in NoSQL databases like MongoDB. In this article, weâll explore some methods for updating
5 min read
How to Push an Array into Object in JavaScript?
To push an array into the Object in JavaScript, we will be using the JavaScript Array push() method. First, ensure that the object contains a property to hold the array data. Then use the push function to add the new array in the object.Understanding the push() MethodThe array push() method adds one
2 min read
How to Push an Object into an Array using For Loop in JavaScript ?
JavaScript allows us to push an object into an array using a for-loop. This process consists of iterating over the sequence of values or indices using the for-loop and using an array manipulation method like push(), to append new elements to the array. We have given an empty array, and we need to pu
3 min read
How to Update Deeply Nested Array in MongoDB/ Mongoose ?
In MongoDB/Mongoose, updating deeply nested arrays can be challenging due to the nested structure. This article will explore various approaches to update deeply nested arrays efficiently using both MongoDB queries and Mongoose methods. Explaining each approach one by one below: Table of Content Usin
2 min read
How to create an id using mongoose in Javascript?
Mongoose is a powerful tool that simplifies MongoDB operations by providing a structured way to define schemas and models. With Mongoose, developers can define relationships between data, apply validation rules, and create reusable query logic. In this article, We will learn about Mongoose, Defining
5 min read
How to Register and Call a Schema in Mongoose?
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward and schema-based solution to model our application data. Understanding how to properly define and work with Mongoose schemas is essential for efficient MongoDB management and data interac
5 min read
How to Join two Schemas in Mongoose?
Mongoose is a popular MongoDB object modeling tool for Node.js that simplifies data manipulation. However, developers often face challenges when trying to join two schemas in Mongoose, as MongoDB, a NoSQL database, does not natively support join operations like SQL databases. In this article, We wil
5 min read