Storing an Array of Objects in Mongoose: A Guide

Mon Jan 3, 2022

To store an array of objects in a Mongoose field, you can define the field as an array of a specific sub-schema.

const mongoose = require('mongoose'); const subSchema = new mongoose.Schema({ name: String, age: Number });
const schema = new mongoose.Schema({ myArray: [subSchema] }); const MyModel = mongoose.model('MyModel', schema);

This will create a new Mongoose model called "MyModel" with a field called "myArray" that can store an array of objects, where each object must have a "name" field of type String and an "age" field of type Number.

You can also use mongoose.Schema.Types.ObjectId to define an array of objects with ids

const mongoose = require('mongoose'); const subSchema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, name: String, age: Number });
const schema = new mongoose.Schema({ myArray: [subSchema] }); const MyModel = mongoose.model('MyModel', schema);

This will create a new Mongoose model called "MyModel" with a field called "myArray" that can store an array of objects, where each object must have a "name" field of type String, an "age" field of type Number and an _id field of type ObjectId

You can then use the Mongoose model to interact with the database and perform CRUD operations on the array of objects.

DCT Academy
Full Stack web development training institute in Bangalore

Launch your GraphyLaunch your Graphy
100K+ creators trust Graphy to teach online
𝕏
Best MERN Full Stack Development Course | Bangalore | Offline | Online | 100% Placements | Training Institute | Front End Course | React JS Training | Online Course India 2024 Privacy policy Terms of use Contact us Refund policy