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
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
Contact Us