How to push or pull item from an array in Mongoose

There are two ways to push an item to an array in Mongoose. The simplest way is to retrieve the document from MongoDB, push new items into the array, and then call the save() method to update the document.

Let us say that you have got the following Student model:

const mongoose = require('mongoose')
const { Schema } = mongoose

const Student = mongoose.model(
  new Schema({
    name: String,
    friends: [String]

The following example demonstrates how you can append new items into an array in Mongoose:

// Create new document
await Student.create({ _id: 1, name: 'John Doe', friends: ['Alex'] })

// Retrieve document
const doc = await Student.findOne({ _id: 1 })

// Append items to `friends`

// Update document

The second method to append an item into an array is using the $push operator. The $push operator appends specified items into an array without loading them first into memory as shown below:

await Student.updateOne({ _id: 1 }, { $push: { friends: 'Maria' } })

To append multiple items at once, use $push with the $each modifier:

await Student.updateOne({ _id: 1 }, { $push: { friends: { $each: ['Maria', 'Jovan'] } } })

Similarly, to remove items from an array, MongoDB provides the $pull operator. It removes from an existing array all instances of a value or values that match a specified condition:

// Remove single item
await Student.updateOne({ _id: 1 }, { $pull: { friends: 'Alex' } })

// Remove multiple items with `$in` modifier
await Student.updateOne({ _id: 1 }, { $pull: { friends: { $in: ['Maria', 'Jovan'] } } })

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.