The parent-child relationships in MongoDB

In my Meteor application, I have created two collections: ActivityCards and Users. Inside the ActivityCard collection, there is a reference to the User like this:

 {
    "_id" : "T9QwsHep3dMSRWNTK",
    "cardName" : "Guntnauna",
    "activitycardType" : 10,
    "startDate" : "1952-08-09",
    "remainingHours" : 0,
    "activities" : [ 
      {
        "activityName" : "Cfuw",
        "activityTotal" : "5",
        "activityEmployee" : "Smamnktl",
        "activityDate" : "1960-07-16"
      }, 

      ... 
    ],
    "customerID" : "z9hXczmWaf7wgdAtj",
    "isArchived" : 0
}

The customerID field holds an ID that corresponds to the following user collection:

{
    "_id" : "9mXAZkmfpKMPvQY8Y",
    "createdAt" : ISODate(),
    "services" : {
      "password" : {
        "bcrypt" : ""
      }
    },
    "emails" : [ 
      {
        "address" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f5eef1eeeff8c1ece0e8ede8efe0f5eef3afe2eeec">[email protected]</a>",
        "verified" : false
      }
    ],
    "profile" : {
      "relationNumber" : "962",
      "companyName" : "Snider Kinney Co",
      "locationStreet" : "Ullamco eaque consequatur aspernatur consectetur eiusmod eligendi enim rerum consectetur asperiores officia eius itaque expedita dolorum",
      "locationPostal" : "Sit inventore asperiores est anim commodo non fugiat consequat Voluptatem tempore sunt culpa magni",
      "locationCity" : "Ipsum et fugit pariatur Nobis eveniet neque veniam perferendis eius ut quo excepteur consequatur voluptatem architecto",
      "contactName" : "Julian Moran",
      "contactPhone" : "+388-14-8339022",
      "isArchived" : 0
    },
    "roles" : {
      "customers" : [ 
        "customer"
      ]
    }
} 

As a newcomer to MongoDB, I am unsure if this relationship is properly configured. Most of the documentation I've come across discusses parent-child relationships, not the reverse.

I would appreciate any suggestions on how to handle this type of relation, including saving the data, retrieving it from both collections, etc.

If possible, I would like guidance on accessing relations from child to parent and displaying them. Currently, I am using the find() method from MongoDB and mapping the data into separate values.

Answer №1

In your mongodb collection, it is possible to establish such a relationship. If you are using mongoose, you can specify them in your schema as shown below:

customerId:{{ type: mongoose.Schema.ObjectId, ref: 'user' }}

You can then access the parent from the child using mongoose populate. For additional details, refer to

https://mongoosejs.com/docs/populate.html

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

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

Is it possible to adjust the size of a p5.js canvas within a bootstrap Div container?

I am attempting to incorporate a p5js canvas into a bootstrap grid structure. My goal is to have each div within the grid contain its own unique p5js canvas, which should adjust in size when the browser is resized. Below is my bootstrap grid setup, showca ...

How can I retrieve data from local storage based on a specific key value using a query?

In order to optimize the storage of data for my app, I have successfully stored a large amount in local storage. Now, I am faced with the task of fetching data in an array but only selecting key/values that are specifically chosen, rather than all or jus ...

What could be causing this JavaScript code to run sluggishly in Internet Explorer despite its simple task of modifying a select list?

I am currently developing a multi-select list feature where users can select items and then rearrange them within the list by clicking either an "Up" or "Down" button. Below is a basic example I have created: <html> <head> <tit ...

Simultaneously sending jQuery.ajax data while submitting a form

I'm facing a bit of a dilemma here. I have a form with multiple fields, including one for entering links. When you input a link and click the add button, the link is added to a link_array using jQuery. My goal is to send this array through the jQuery. ...

The hyperlink element has been added but is not clickable

I'm attempting to incorporate a download feature into my webpage using Greasemonkey. Despite successfully adding the new div element to the page, I am encountering an issue where the download window does not open as expected. var iDiv = document.crea ...

Having trouble with fs.readFile in Node.JS on Ubuntu?

Currently, I am facing an issue when trying to read XML files. Strangely, the code works flawlessly on my personal computer running OS X. However, when I run the same code on a DigitalOcean Ubuntu 16 Server, it fails to produce any results. I am utilizing ...

"Exploring the World Wide Web with Internet Explorer Driver and Webdriver

After trying everything I know to make internet explorer work with webdriver.io, I've encountered a confusing issue. To start, download the internet explorer driver from this link: http://www.seleniumhq.org/download/. The file is an .exe named ' ...

Querying MongoDB in Node.js

I run a movie website. When users watch videos, I want to display the following information: From the video collection, I need to retrieve: All fields by ID (with the foreign key stars_ID) The top 10 most-watched videos of the week 20 movies featuring t ...

Is it possible for the router to hold off until a promise is fulfilled before proceeding?

After implementing the code snippet provided by express router, an error occurs when trying to use another async function. The specific error message is: Error: Can't set headers after they are sent. Interestingly, upon removing the line await anot ...

Can you explain the distinction between these two forms of functional components in ReactJs?

What sets apart these two code usages? In the FirstExample, focus is lost with every input change (It appears that each change triggers a rerender).. The SecondExample maintains focus and functions as intended. example import React, { useState } from &quo ...

Exploring FindAll functionality in the C# MongoDB driver

Currently, I am trying to execute a "find all" query using the most recent version of the C# MongoDB driver. The code snippet I am working with looks something like this: var xx = _context.NLMCDatabase.GetCollection<BsonDocument>("Requestables").Fi ...

What is the proper way to input information into fields during an update?

Let's talk about a scenario: I have a form created using Material UI components (TextFields) that I want to use for both creating and updating products. The product creation part of the form is working well, except when no image is added. For updati ...

How can you retrieve a value from a JavaScript closure function?

I'm struggling with getting a value from a closure function in Javascript. In my initial attempt, I placed the return statement inside the inner function, but it was not effective. Then, I tried moving the return statement to the outer function, howev ...

Is there a way to block the .load() function directly from the browser console?

I am looking to enhance the user experience on my website by dynamically loading certain content after login. This involves using a $.post(...) method to interact with a servlet that verifies the user's credentials, followed by a $.load(url) function ...

I am interested in altering the color of table rows using either JQuery or CSS

Looking to update row colors based on grouping. For example: Color the TR accordingly for every 5 rows: First 5 rows in green (0-4 Rows), Next five rows in red (5-9 Rows), Following five rows in yellow (10-14 Rows) and repeat the pattern... ...

Display information from dynamically generated pages using Gatsby JS sourcing data from CSV files

I've been working on creating pages in Gatsby JS from a csv file and everything seemed to be going smoothly. However, when it comes to displaying the data on these generated pages, I keep running into issues with undefined variables and can't see ...

Concealing certain columns when the table exceeds a certain size

Hello everyone, I am just starting out in the world of React and web applications. Please feel free to reach out if anything is unclear to you. Here is the table structure that I currently have: <div> <table id="mytableid" className=&qu ...

Determine total number of covid-19 cases with JavaScript

I am looking to incorporate a real-time COVID-19 total cases tracker for Russia on my website. In order to achieve this, I am sending a request to using the following script: function httpGet(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.o ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...