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