What is the best way to access my question model in Mongoose and Express?

Seeking to access the Question model's text referenced in the Survey model, particularly the QuestionText. While I am able to retrieve the question ID successfully, obtaining the QuestionText using

SurveyList[count].Questions.QuestionText

does not work as expected.

However, this line does function correctly:

SurveyList[count].Questions._id

The complete front-end code snippet is provided below:

<!-- All Surveys -->
<% for (let count = 0; count < SurveyList.length; count++) { %>
    <tr>
    <!-- Display title -->
        <td class="text-center text-white"><%= SurveyList[count].Title %></td>
        <!-- Display type -->
        <td class="text-center text-white"><%= SurveyList[count].Type %></td>
        <td class="text-center text-white"><%= SurveyList[count].Questions._id %></td>
<% } %>

Details of my Question Model Schema are outlined below:

// Define the question model
let questionModel = mongoose.Schema(
  {
    
      QuestionText: String,
      Options: String,
   
  },
  {
    collection: "questions",
  }
);

Information regarding my Survey model schema is presented here:

let surveyModel = mongoose.Schema(
  {
    Title: String,
    Type: [String],
    Questions: { type: mongoose.Schema.Types.ObjectId, ref: "questions" },
    Answered: { type: Number, default: 0 }, // number of user responses
    DateCreated: { type: Date, default: Date.now }, // date created
    Lifetime: { type: Date, default: Date.now }, // Survey expiration date
  },
  {
    collection: "surveys",
  }
);

Controller logic for displaying live surveys is included below:

module.exports.displayLiveSurveys = (req, res, next) => {
  Survey.find((err, surveyList) => {
    if (err) {
      return console.error(err);
    } else {
      
      res.render("content/survey/live-surveys", {
        title: "Live Surveys",
        page: "live-surveys",
        username: req.user ? req.user.username : "",
        SurveyList: surveyList,
      });
    
    
    }
  });
};

If there is a way to reference Question.find within Survey.find and append QuestionList to res.render, that could be advantageous. Attempted implementation did not yield desired results.

Data payload for a Survey object:

{
    "_id": {
        "$oid": "60fd0c7ecd479a846f1f0fe5"
    },
    "Type": ["TF"],
    "Answered": {
        "$numberInt": "0"
    },
    "Title": "hello",
    "Questions": {
        "$oid": "60fd067d736566143839e3fd"
    },
    "DateCreated": {
        "$date": {
            "$numberLong": "1627195005136"
        }
    },
    "Lifetime": {
        "$date": {
            "$numberLong": "1627195005136"
        }
    },
    "__v": {
        "$numberInt": "0"
    }
}

Question data payload:

{
    "_id": {
        "$oid": "60fd0cbacd479a846f1f0fe6"
    },
    "QuestionText": "test",
    "Options": "tester",
    "__v": {
        "$numberInt": "0"
    }
}

Answer №1

Utilize the $lookup method to effortlessly merge documents from two collections when manual referencing is in play.

The query will appear as follows:

db.survey.aggregate([
  {
    "$match": {
      _id: ObjectId("60fd0c7ecd479a846f1f0fe5")
    }
  },
  {
    $lookup: {
      from: "question",
      localField: "Questions",
      foreignField: "_id",
      as: "Questions"
    }
  }
])

To test out your scenario, visit this link to the playground: Mongo Playground

OR

If you prefer using DBRefs, your survey document will be structured like so, with the driver handling reference resolution automatically:

{
    "_id": ObjectId("60fd0c7ecd479a846f1f0fe5"),
    "Type": ["TF"],
    "Answered": 0,
    "Title": "hello",
    "Questions": {
        // This represents a DBRef
        "$ref" : "question",
        "$id" : ObjectId("60fd0cbacd479a846f1f0fe6"),
        "$db" : "sample"
    },    
    "DateCreated": 1627195005136,
    "Lifetime": 1627195005136,
    "__v":  0
}

For further insights on $lookup and $ref, refer to the official documentation

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

How can ReactJS continuously dispatch promises after a set interval?

Within my React component, I am invoking an action in ComponentDidMount() as shown below: componentDidMount() { const { actions } = this.props function save_project_continuously() { console.log("inside") actions.sa ...

Trying out $window.location.href in Karma with Angular testing

I'm currently working on properly injecting the $window service into my Angular controller, and then testing to ensure that it redirects correctly. However, I'm running into an issue where I'm getting an error message that says undefined is ...

How can JavaScript be used to identify duplicate elements within an array?

In a recent interview, I was tasked with finding repetitive elements in an array. While I was able to do so using a for loop, the interviewer requested a more efficient method without using a for loop. I am relatively new to exploring Java script and would ...

Guide on exporting a reducer from a Node module built on React Redux

I am currently working on a project that requires importing a component from an external node module. Both the project and the component utilize React and Redux, and I intend for them to share the same store. Below is a snippet of the reducer code for the ...

Retrieve the top-level property name in an object literal when using *ngFor

I am currently utilizing lodash for grouping items by their 'module' property. The code snippet I am using is as follows: _.groupBy(_.flatten(this.postReleaseArr), 'module'); This code returns the following image: https://i.sstatic.ne ...

Possible performance problems in NodeJS project with MongoDB due to possible neglect of projection when using native MongoDB driver

Detailed Explanation: (For quick summary, scroll down to TLDR) Within my collection 'libraries', there exist two types: "template" and "standard-template". A library can either be owned by an organization, in which case it will have an "organiza ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Can Discord.JS add roles, but struggle with removing them?

I've been grappling with this code snippet for quite some time now. Adding the role works fine, but removing it seems to be a challenge as there are no errors thrown and the role remains intact. Despite searching online for solutions, none seem to ad ...

JavaScript and jQuery syntax are essential for web development. Understanding how

I've been searching everywhere but couldn't find syntax similar to this: var mz = jQuery.noConflict(); mz('#zoom01, .cloud-zoom-gallery').CloudZoom(); This basically means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery') ...

Issue with AngularJS UI Router not loading the inline template and controller

I am trying out UI Router for the first time in my AngularJS project. I am facing an issue where, when I click on a link to view a post, it doesn't display. The post template is not visible and I remain on the home page. The URL flashes as http://loc ...

Rotating an object in Three.js: Animate back and forth along two different azimuth angles

My three.js project features a 3D object that is meant to be viewed from the front only, as it appears as a single plane and is transparent from the back... Using orbitControls, I have restricted movement of both azimuth and polar angle... To enhance the ...

"Exploring the concept of master pages in web development with the combination

Recently, I have been developing a website that functions similarly to olx, displaying ads based on the visitor's location (for example, showing Mumbai ads if the visitor is from Mumbai). Initially, I was planning to create separate pages for each cit ...

Numerous unique designs paired with exclusive paths

I am working on setting up a system that accommodates multiple layout variations and includes private routes to display specific content based on the user's login status and assigned layout. Currently, I have three different layouts in place, with the ...

"Express API POST request functions successfully on Postman, however encounters difficulties when used with AJAX

My goal is to send an AJAX request from JavaScript to my ExpressJS Rest API. Unfortunately, the POST call is not working in JavaScript. Interestingly, when I use Postman, the same JSON data with the same headers works perfectly. Here is the error I&apos ...

Is it guaranteed that Github dependencies will always be accessible in the future?

After spending a few years as a Javascript / NodeJs developer, I am currently diving into learning Go. It is a whole new world for me. One interesting aspect of Go is that most external dependencies are pulled directly from Github. This raises the questi ...

A guide to integrating ffmpeg with NuxtJS

I am completely new to Nuxt and currently in the process of migrating a Vue application that generates gifs using ffmpeg.wasm over to Nuxt.js. However, every time I try to access the page, the server crashes with the following error message: [fferr] reques ...

PHP script failing to execute if/else statement during AJAX request

I am currently developing a website that heavily relies on Ajax, and I have chosen to use codeigniter for its construction. On the site, there is a form with the post method, and this form is submitted using an Ajax request that calls a function containi ...

The chat message section is failing to update due to AJAX not refreshing

I recently launched a new website and am facing challenges with the chat feature. Despite using ajax to update the chat messages without refreshing the page, the other user still needs to refresh in order to see the latest message. We are both in the sam ...

Utilizing AJAX to load a WAV file

One of the tasks I'm working on involves a collection of audio files. When a file from this list is clicked, I want JavaScript to load and display the waveform of that specific audio file. The following function is responsible for drawing the wavefor ...