"Sharing fields between mongoose models: How can I reference a field from one model in another

I am currently working on linking specific fields from the User model to the Card schema using the username as a reference point. Let me provide an example using my Card schema:

 const CardSchema = new mongoose.Schema({
      text: {
        type: String,
      },
      username: {
       type: String,
       ref: 'User',
       required: true
      },
      userSticker: {
       I need to extract this information from the user model based on either the username or user ID.
      }

Now, let's take a look at how the user model is structured:

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
  },
  userSticker: {
   type: String,
  }

Essentially, what I am trying to achieve is to always have the same userSticker value in the Card schema as the corresponding user in the User model. Simply adding it upon card creation won't suffice since the userSticker may change over time. Therefore, I am looking for a solution that will dynamically update the field in the Card schema whenever the associated user's userSticker changes - perhaps through some form of reference implementation.

Answer №1

Exploring the wonders of mongoose with insights from its official documentation Query Population

 const cardSchema = new mongoose.Schema({
      text: {
        type: String,
      },
      username: {
       type: String,
       ref: 'User',
       required: true
      },
      userSticker: {
       type: Schema.Types.ObjectId, 
       ref: 'User'
      }
};

const userSchema = new mongoose.Schema({
  username: {
    type: String,
  },
  userSticker: {
   type: String,
  }
}

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

Card.findbyId(id).populate('userSticker', 'userSticker').exec(function(err, card) {/* Carry out actions... */})

Answer №2

UPDATE: After some research, I've discovered that mongoose handles relational data modeling by allowing you to define references in the schema.

For more information, check out this resource: Relational database design to mongoDB/mongoose design

This section pertains to MongoDB specifically

Since MongoDB is not a relational database like SQL, there are two common solutions:

The first solution involves duplicating data and updating all related fields when changes occur:

const CardSchema = new mongoose.Schema({
  text: {
    type: String,
  },
  username: {
    type: String
  },
  userSticker: {
    type: String,
  }
})

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
  },
  userSticker: {
    type: String,
  }
})

Whenever the userSticker changes, you would need to query the card collection and update all matching userStickers.

The second solution requires manually creating a reference between collections:

const CardSchema = new mongoose.Schema({
  text: {
    type: String,
  },
  user_id: {
    type: String,
  }
})

const UserSchema = new mongoose.Schema({
  _id: {
    type: String,
  },
  username: {
    type: String,
  },
  userSticker: {
    type: String,
  }
})

When querying the document in the card collection, a second query can be made for the document referenced by user_id.

  • The first solution is slower on write but faster on read.
  • The second solution is faster on write but slower on read (especially when paginating queries).

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

Encountering a CORS issue while attempting to make a GET request to an API in an

Looking to retrieve HTML data from a website using an API. The target URL is: https://www.linkedin.com/ Trying to fetch the HTML page as text from this specific URL. Here's what I attempted: getData() { const api = "https://www.linkedin. ...

Learn the process of downloading a pdf file with vuejs and bootstrap-vue

Having trouble uploading a PDF file to my browser and then downloading it afterwards. The upload is fine, but the download isn't working. This is how I am uploading: <b-form-file v-model="form.file" :state="Boolean(form.file)" placeholder="Choose ...

Exploring the world of unit testing with Jest in Strapi version 4

In my quest to conduct unit tests using Jest for the recently released version 4 of Strapi, I have encountered some challenges. The previous guide for unit testing no longer functions as expected following the latest documentation updates. Despite my effor ...

Encountering difficulty in adding content to a table using JavaScript. An error message appears stating that assignment to a function

I am utilizing ajax to retrieve an item from a web API, and then attempting to allocate attributes of that item to a table: function find() { var id = $('#contentID').val(); $.getJSON(uri + '/' + id) .done( ...

Does one require the express.js framework in order to create a web application using nodeJS?

Exploring the creation of a basic web application using HTML, NodeJS, and Postgres. Can this be achieved without incorporating the ExpressJS framework? Seeking guidance on performing CRUD operations with NodeJs, Javascript, and Postgres sans ExpressJS. G ...

CORS blocked the JavaScript Image's request

I am encountering an issue with my code that involves capturing selected divs using the HTML2Canvas library. However, when I try to download the captured image file, it is not working as expected. The error message I keep receiving is "Access to Image at ...

Making HTTP requests with axios in Node.js based on multiple conditions

I'm facing an issue with making get calls using axios to both activeURl and inactiveURl. The goal is to handle error messages from the activeUrl call by checking data from the inactiveUrl. However, I keep receiving error messages for the inactiveURL e ...

Increasing Asynchronous Capabilities with Dynamically Updating jQuery Deferred within then() Method

I am currently exploring the functionalities of jQuery Deferred and I have encountered a challenge regarding chaining multiple deferreds. Let me outline my simplified issue: var def1 = $.ajax(...); // executing ajax call 1 var def2 = null, def3 = null; $ ...

Is the "json_encode" function dropping the '+' character when using "json.parse"?

Seeking Assistance I have a question regarding the functionality of php function json_encode and js JSON.parse. I seem to be encountering an issue where the '+' character is being dropped somewhere in the process, particularly when dealing with ...

Exploring the fundamentals of Express.js code base

I have been examining the express.js code and attempting to rewrite it to gain a better understanding of creating middlewares within a framework. However, the complex inheritance structure in the code is causing confusion for me. Here are some relevant co ...

Obtain the position and text string of the highlighted text

I am currently involved in a project using angular 5. The user will be able to select (highlight) text within a specific container, and I am attempting to retrieve the position of the selected text as well as the actual string itself. I want to display a s ...

Refresh Vue/Nuxt Components Fully

Understanding how this.$forceUpdate() functions, I am not simply looking to re-render the component. In Nuxt applications, page components have asyncData() as a lifecycle method that runs before created(). I utilize this method to retrieve initial data an ...

Why is my React component not being updated with Routes?

I'm new to using react-router and I'm struggling with it for the first time. Here is the code snippet: App.tsx import React from 'react'; logo = require('./logo.svg'); const { BrowserRouter as Router, Link, Route } = require ...

Web Security Vulnerability: Cross Site Scripting Detected

In our code, we are aiming to prevent XSS (Cross Site Scripting) attacks. However, the solution may involve a combination of JS (JavaScript) and HTML escaping, which could prove to be quite challenging. Below is a snippet that closely resembles our code: ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

The random quote generator or current tweet quote feature is malfunctioning

I am having trouble with a jQuery on click function that is not working to tweet the current quote. I am working on building a random quote machine and tweeting the current quote is essential. Despite successfully implementing the JSON API, I cannot seem t ...

send data to a hyperlink

I need to pass a parameter to the href based on the first name in the list. The names are links to another page that I retrieve via an _id passed in the URL. The issue I am facing is that the id is not being passed to the URL, resulting in an error. How ...

Using the "OR" operator in regular expressions within express routing

When a user enters either "/" or "/home" path, I want them to be directed to the same page ("/home"). How can I achieve this using regex in express routing? I attempted the following code but it did not work: router.route('/|/home') ...

Updating the value within a nested array in a ReactJS application

Check out the working code here: https://codesandbox.io/s/broken-https-2i454?file=/src/App.js I'm currently using Material UI within my reactjs project and facing an issue updating the value entered in a textfield of a table using the onChange functi ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...