Sling Academy
Home/Node.js/Using Array schema type in Mongoose

Using Array schema type in Mongoose

Last updated: December 30, 2023

Introduction

In MongoDB, arrays are a powerful feature allowing you to store multiple values in a single key. Mongoose, the popular ODM for MongoDB in Node.js, offers a comprehensive set of features to define and manipulate such arrays using the Array schema type. This guide aims to provide you with the knowledge to make full use of array types in your Mongoose schemas with a progressive step-by-step approach, enriched by real-world code examples.

The Basics

Defining Array Types

At the most basic level, defining an array type schema in Mongoose is straightforward:

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

const userSchema = new Schema({
  hobbies: [String] // Array of strings
});

const User = mongoose.model('User', userSchema);

Working with Arrays

Once defined, you can easily interact with array fields like any other data type:

const newUser = new User({
  hobbies: ['reading', 'gaming', 'jogging']
});

newUser.save();

To add or remove items from the array, Mongoose provides you with methods like push, pull, and splice.

// Add new items
newUser.hobbies.push('coding');
// Remove an item
newUser.hobbies.pull('jogging');
// Save the changes
await newUser.save();

Advanced Features with Arrays

Mongoose also supports more complex array configurations, including arrays of subdocuments:

const itemSchema = new Schema({
  name: String,
  quantity: Number
});

const listSchema = new Schema({
  items: [itemSchema]
});

const List = mongoose.model('List', listSchema);

Manipulating the subdocuments within an array follows a similar pattern:

const newList = new List({
  items: [{ name: 'Bread', quantity: 2 }]
});

// Add a subdocument
ewList.items.push({ name: 'Butter', quantity: 1 });

// Example of updating a subdocument
const item = newList.items.id(subDocId);
item.quantity = 5;

await newList.save();

The conservation of space prohibits a full deep dive, but other considerations include schema validation, querying arrays, and complex operations like aggregations which are beyond the scope of this introduction.

Conclusion

In conclusion, by utilizing the Array schema type in Mongoose effectively, you can unlock the potential of MongoDB’s array data fields. We’ve covered the basics, delved into more complex scenarios, and hinted at advanced use cases like validation and aggregation. Continued learning and practice will foster the expertise necessary to leverage arrays to their fullest within your Node.js applications using MongoDB and Mongoose.

Next Article: Using Mixed Schema Type in Mongoose

Previous Article: Exploring Mongoose ObjectId schema type

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates