Creating a Mongoose schema to reference an array of sub-document IDs from an external collection

My database schema involves managing families with children enrolled in school. Here's an example schema for the family:

var familySchema = new Schema({
    parents: [{
        firstName: String,
        lastName: String,
        email: String,
    }],
    students: [{
        firstName: String,
        lastName: String,
        grade: Number,
    }]
});

Now, I want to design a schema for schools that include classrooms containing students. This is how I envision it:

var schoolSchema = new Schema({
    name: String,
    street: String,
    classrooms: [{
        classroomNumber: Number,
        students: [ /* Unsure about this part */ ]
    }]
});

How can I specify to mongoose that I want an array of object IDs referencing students from the family collection?

I came across this answer which explains how to reference documents from another collection like families:

families: { type : ObjectId, ref: 'Family' }

But how do I achieve the same for sub-documents belonging to another collection? As a beginner in mongo and mongoose, I'm seeking clarity on this.

Answer №1

To implement sub-documents using reference, it is necessary to update the reference to the 'student' array.

const studentSchema = new Schema({
    firstName: String,
    lastName: String,
    grade: Number,
});

const familySchema = new Schema({
    parents: [{
        firstName: String,
        lastName: String,
        email: String,
    }],
    students: [studentSchema]
});

const schoolSchema = new Schema({
    name: String,
    street: String,
    classrooms: [{
        classroomNumber: Number,
        students: [{ type: ObjectId, ref: 'Family.students' }]
    }]
});

const Student = mongoose.model('Student', studentSchema );  
const Family = mongoose.model('Family ', familySchema ); 
const School = mongoose.model('School', schoolSchema );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Power of Multiple FindOne Queries in MongoDB

I have been working on expanding the data fields returned by our API. Currently, the API retrieves student information using the find method, and also includes some project details by retrieving the student info and using findOne to obtain information abou ...

JavaScript Regular Expression that identifies commas enclosed within quotation marks

I am attempting to parse a text-based log file in the following format: type: 'click', category: 'REFRESH_DOOR', desc: 'clicked refresh from door 0124', site: 'mysite', pathname: '/load_areas/all/doors&apos ...

Showing information from a database while incorporating line breaks with the help of nl2br

Having trouble with the previous question, so I'll provide more detail here. Below is my index.php file where I explain the method used to save data to a database. <html> <head> <script> function updategroup() { var update_c ...

Utilizing dual functions within the onChange event handler in React

I have a situation where I need to pass a function from a parent component to a child component through the onChange event, as well as another function in the child component to update its own state. How can I achieve this? Parent export function Fruits() ...

What role does the conditional statement play in the function ExtrudeGeometry.UVGenerator.generateSideWallUV within three.js?

Within three.js's ExtrudeGeometry.UVGenerator.generateSideWallUV function, there is a specific condition being checked: if ( Math.abs( a.y - b.y ) < 0.01 ) { return [ new Vector2( a.x, 1 - a.z ), new Vector2( b.x, ...

collaborate and coordinate a territory among various components on a map

I'm currently working with an array of elements that are being drawn on a canvas. export function useCanvas(){ const canvasRef = useRef(null); const [ elements, setElements] = useState([]); const [ isHover, setIsHover] = useState(false); ...

The JavaScript file specified in the script tag's src attribute was successfully downloaded, but it did not execute as expected after being fetched

I've implemented an ajax call using jQuery in the following manner: $.ajax({ type: 'GET', url: 'edit.htm', success: function(data){ container.html(data); }, }); After making the ajax call, the data returned includes s ...

What is the best way to coordinate text and photos within Bootstrap?

Currently, I am working on a bootstrap website that features a slideshow with 3 photos. The jQuery function responsible for this is as follows: $(function () { $.vegas('slideshow', { backgrounds: [{ src: 'img/ph1.jpg ...

Methods to fix the error of "unspecified name" in Postman while accessing the Heroku URL with NodeJs and MongoDB

I'm navigating my way through Heroku, NodeJS, and MongoDB for the first time. I've set up a login form in Flutter with a backend in NodeJS and MongoDB. Utilizing Heroku to connect the backend to Flutter, however, when I try to access the URL (pro ...

JavaScript shortening a string while joining it

I'm facing a challenge with string truncation in my laravel and JS(jquery) app. Initially, I suspected it was an issue with the backend (as indicated in my question here: Laravel Truncating Strings). However, after thorough debugging, I discovered tha ...

Can you configure the redux store once and share it across different pages?

I have a redux store where the state is in the form of {names:[], address:[]}. Across multiple pages, both names and address are used as properties. However, I find myself making API calls on each page to fetch these values which is causing unnecessary n ...

Dealing with 'ECONNREFUSED' error in React using the Fetch API

In my React code, I am interacting with a third party API. The issue arises when the Avaya One-X client is not running on the target PC, resulting in an "Error connection refused" message being logged continuously in the console due to the code running eve ...

"Troubleshooting: Shadows are not appearing on Three.js OBJLoader .obj models

I'm currently tackling a project in which I want to enable a .OBJ model loaded from OBJLoader.js to cast a shadow from a spotlight. The light successfully casts shadows from other regular objects, however, the .OBJ model doesn't seem to be castin ...

How can I feature an image at the top of the page with large 3 and jQuery in FireFox?

I am interested in showcasing a single image at the forefront of the page when it is selected. While there are numerous plug-ins that offer this feature, many come with unnecessary extras like galleries, video support, and thumbnails which I do not requir ...

Using GeoJson in Leaflet for map display

As I develop an Angular application with Leaflet, my goal is to showcase numerous municipalities within my country: https://i.sstatic.net/9cuSW.png In order to enhance navigation efficiency, I decided to divide my JSON file into multiple files and store ...

What is the best way to retrieve the Axios Post response in React?

I'm facing a small issue. In my ReactJS code, I have a post function that is functioning correctly. However, I want to access the response of this function outside its scope, right where I called it. Is there a way to achieve this? async function che ...

Tips for creating a floating Tooltip that follows the Cursor on a wider element

In my application, I have a Gantt chart with horizontal scrolling capabilities. Users can navigate through the chart by using the scrollbar, drag and drop feature, or mouse wheel. The scrollable area of the Gantt chart can be very wide, spanning thousands ...

In JavaScript, the JSON Object only stored the final result from a loop

I am currently working on an HTML Site that features 4 inputRange sliders. My goal is to store all values from these sliders in a nested JSON Object when a user clicks on a button. However, I have encountered an issue where my JavaScript code only saves th ...

How can we send an array using JavaScript and Ajax without relying on JQuery?

When I call a PHP function using Ajax: var ajax = new XMLHttpRequest(); ajax.open("POST", "file.php", true); ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajax.onreadystatechange = function(){ if(ajax.readyState == 4 &am ...

Error: Unable to assign value to property 'className' of undefined object

On my http://localhost:3000/renewal page, the code looks like this: import Link from 'next/link' export default function Renewal() { return ( <header> <Link href="/"> <a> Go to home page ...