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.