"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

The default choice vanishes once a non-empty option is chosen

Here is a simple example illustrating my issue: JSFiddle. Initially, I have an empty/default option, but when I select something else from the drop-down, this default option disappears. How can I keep this default option visible after making a selection? ...

I'm experiencing difficulties in retrieving my request body parameters despite using express.json()

I am facing an issue with my app.ts file. I have the following code, but when I try to access the body of my request, it returns undefined. import { Request, Response, NextFunction, Application } from 'express'; import express from 'express& ...

Move files in Node.js without removing the original source directory

Currently, I am facing an issue while attempting to transfer files from one directory to another using the mv module. The problem arises when the files are successfully moved, but the source directory is automatically deleted. My intention is for only the ...

Node.js: Array remains undefined despite being logged on the console

My goal is to download a CSV file, read it line by line, and add the split lines (based on ',') to the tmparray. This code successfully prints all the elements in the array. var request = require('request'); var fs = require('fs&a ...

Sending Ajax data to a controller function

I am looking for guidance on how to pass values from my view to my controller using ajax. As someone who is new to working with ajax, I would appreciate some assistance in understanding the process. Full Page @model ALSummary.Models.MonthReport @{ ...

Currently, I am utilizing Angular 2 to extract the name of a restaurant from a drop-down menu as soon as I input at least two characters

I am currently utilizing Angular 2 and I am trying to retrieve the names of all restaurants from a dropdown menu. Currently, when I click on the text field, it displays all the results, but I would like it to only show results after I have entered at least ...

Retrieve information and display it in a text field using ajax

Hi there, I'm having some trouble with my current code and would appreciate any help you can offer. My goal is to filter data in a search box and display the corresponding results in text boxes. I've been searching online for hours trying to find ...

Incorrect character set used in jsonp ajax requests

My ajax request implementation looks like this: function apiCall(resource, data, callback) { if(data == undefined || data == null) data = {}; $.ajax({ dataType: 'jsonp', data: data, url: nodeUri + "/" + resource }). ...

Triggering Firebase Cloud Functions upon a database event to perform a redirect

Typically, one would use an https trigger in Firebase Cloud Functions for redirection, as shown below. exports.redirect = functions.https.onRequest((request, response) => { response.redirect("laserguidedmissiles.com") }); But how ...

Error: Node application using Express does not display 'Server Started' message in console upon execution

I'm encountering an issue where I don't see the "Server Start: 3001" message on the console when I run 'node app.js' in the terminal. Below is the content of my app.js file: var createError = require('http-errors'); var exp ...

Utilizing vue-router to create two separate navigation bars where only one link is highlighted as active

In my setup, I have implemented two sections with navigation structured as follows: <ul class="navigation-list"> <li v-for="(route, index) in navRoutes"> <router-link :to="route.path"> <span>{{ route.name }}</span> ...

An unexpected issue occurred while converting XML data into JSON format

I have been using a piece of code that converts XML to JSON: // Converting XML to JSON var XmlToJson = function xmlToJson(xml) { //console.log('called xmltojson'); //console.log(xml); // Creating the return object var self = this ...

What is the best way to pass default event argument alongside another argument in React?

This snippet demonstrates the function I wish to call when a certain input type is invoked: _handleOnEnterPress = (e, receiverUserId) => { if (e.keyCode === 13) { // assuming keycode 13 corresponds to 'enter' console.log("pressed ...

Tips on utilizing a function that was generated within the constructor

I'm currently in the process of developing a function within the constructor, and it is essential that this function be placed inside the constructor. I am interested in implementing a button to trigger this function from an external source, but unfor ...

Preventing the selection of 'None selected' upon dropdown change

When using the NameTextBox Dropdown, all names are available for selection. Upon changing a name and clicking on search, the associated details are retrieved. However, by default, 'None Selected' is displayed. Is there a way to prevent 'None ...

displaying data once "other" is chosen from a dynamic chart

I am having an issue with a dynamic table where I have a dropdown list with the option "other", and I want to display additional input when "other" is selected. Currently, the function I have only hides the input that is always visible and does not show ...

Mapping DOM elements to VueJS components for hydration is a key process in facilitating

I have a specific requirement and I am exploring potential solutions using VueJS, as it offers the convenient feature of hydrating pre-rendered HTML from the server. In my Vue components, I do not define a template within the .vue file, but I need them to ...

What techniques can be used to ensure an element remains visible within the viewport

I am currently working with an HTML element that is displayed when a button is clicked, similar to a popup. My goal is to determine if the element is within the browser's viewport and then position it accordingly inside the viewport. Is there a proper ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

Limit DerbyJS to re-rendering specific DOM elements

Currently, DerbyJS (visit http://derbyjs.com) functions by replacing everything in the body tag of the document each time a link is clicked. Is there a way to utilize the template, but replace only the content inside #main-content instead of refreshing th ...