Utilize nested schema in Mongoose for data population

I have a User model with the following fields:

  const userSchema = new Schema({
      _id: {
        type: Schema.Types.ObjectId,
        required: true
      },
      name: {
        type: String,
        required: true
      },
      email: {
        type: String,
        unique: true,
        required: true
      },
      notification: {
        experiment_id: {
          type: Schema.Types.ObjectId,
          ref: "Experiment",
          required: false
        },
        seen: {
          type: Boolean,
          required: true,
          default: false
        }
      }
    });

Also, I have an Experiment model defined as follows:

const experimentSchema = new Schema(
  {
    _id: {
      type: Schema.Types.ObjectId,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    description: {
      type: String,
      required: true,
      default: "No Description"
    },
    author_id: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true
    }
);

My goal is to populate the experiment_id in the User's notification field. Moreover, I want to further populate the author_id from this previous population action. I attempted the code snippet below but encountered some issues.

Here is my attempt:

User.find(
  {
    _id: req.params.currentUserId
  },
  "notification"
)
  .populate({ path: "experiment_id", populate: { path: "author_id" } })
  .exec((err, notif) => {

  }); 

Answer №1

The issue was resolved by including notification.experiment_id in the pathway

User.find(
  {
    _id: req.params.currentUserId
  },
  "notification"
)
  .populate({ path: "notification.experiment_id", populate: { path: "author_id" } })
  .exec((err, notif) => {

  }); 

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 I prevent the constant use of "this" when creating functions and variables within objects in JavaScript?

Currently, I am utilizing simple JavaScript objects that contain functions and members. One recurring issue I encounter is having to append the this keyword every time I access a member or function. Adding this repeatedly can be tedious, so I am seeking ...

Implementing a server-side timer in ASP.NET MVC to restrict users from modifying the timer

In my MVC asp.net quiz application, users are given a variable amount of time to complete the quiz. Once this time runs out, their answers will be automatically submitted. As of now, I have set up a timer in Javascript with the duration stored in the Cont ...

Developing a custom edit template with Infragistics through coding

Currently, our team utilizes the Infragistics grid without binding datasets until runtime. Instead, we set up the grid settings in code as per the preference of our senior developer. While effective, this method can seem a bit lengthy. I am interested in ...

Using string.startsWith() with Wildcards or Regular Expressions

Currently in the process of refactoring code that relies on string.startsWith() in JavaScript. The documentation here does not mention the use of wildcards or Regular Expressions with this method. Is there an alternative approach I can take? ...

Dynamic stylesheet in Vue component

Currently, I am utilizing a Vue component (cli .vue) and facing the challenge of selectively displaying my stylesheet based on a boolean value. To put it simply: When myVar==false, the component should not load its styles. <style v-if="myVar" lang="sc ...

Tips for preventing the loss of ajax calls when an Oauth access-token expires

As the creator of a JavaScript browser application (SPA) that communicates with a server protected by OAuth 2, I encounter the challenge of using short-lived access tokens and longer-lived refresh tokens. While this specific scenario involves my own server ...

Persist documents into MongoDB using Mongoose for loading and saving

My current setup involves a node running with express as the server-side framework. I have set up the following endpoint: app.post('/post/save', auth.auth, function (req, res) { Post.findById(req.body._id, function (err, post) { post = post ...

Discover the method for obtaining the data of a specific <div> element based on its ID through JavaScript in an Android WebView

Hello, I am new to web development so please bear with me if my question seems naive. I am currently working on a script using html, css, and js to display a text editor in a webView. The editor is being displayed without any issues, but now I'm facin ...

Unable to retrieve multiple values from a sinon stub

I am trying to stub a method using sinon in my Typescript code with Bluebird promises. However, I'm running into an issue where only the first value I set for the stub is being returned, even though I want it to return a different value on the second ...

Struggling to iterate through the children of a variable with the help of express-handlebars?

Currently, I am in the process of developing an application using Javascript along with express, express-handlebars, and MySQL. One of my main tasks is to establish a route that follows the pattern '/viewowner/:ID/scoreboards/:year' where ID sig ...

Obtaining the calculated background style on Firefox

Back when my userscript was only functional on Chrome, I had a setup where I could copy the entire background (which could be anything from an image to a color) from one element to another. This is how it looked: $(target).css('background', $(so ...

Troubining AJAX for Generating a New Template: Addressing Missing Template Error

I have been working on integrating AJAX into my to-do application, but I keep encountering a missing template error (Missing template items/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :bu ...

Clicking on an ID within a jQuery list will return the value

<ul id='myid' > <li>Apple MacBook Pro</li> <li>Apple iPad Pro</li> <li>Apple iPhone 12 Pro</li> <li>Apple Watch Series 6</li> <li>Apple AirPods Pro</li> </ul> ...

What are the benefits of utilizing Vue.set to mutate Vuex with an observable object?

Looking to achieve: What is the most effective method for updating a specific record within the Vuex state using one bulk write process? Situation: Within the Vuex state, there exists a collection of records each initialized with default values. Approach ...

Creating a Discord Bot: Building an Embed Table/List with Segmented Sections

Currently in the process of learning Javascript and venturing into discord.js, I'm fully aware that the code I am working with is not up to par and requires some serious refinements. The main objective here is to split up the arguments of a command a ...

Invoke the API and display the data once the states have been successfully updated

Upon initialization, the code checks the current role of the user. If the role is admin, the setAdmin(true) function is called to set the state of admin to true. By default, the admin state is set to false. When the component is rendered, it initially di ...

Integrate a variable called "counter" with the jQuery ID

I currently have the following code, which is functioning well. $('.clickable').click(function(e){ e.preventDefault(); $('#toggle').slideToggle(); }); $('.clickable1').click(function(e){ e.preventDefault(); $('# ...

Both position absolute and position relative are failing to work effectively

Whenever I click on a div called "test", another div named "outside" appears, along with a div named "inside" that has a higher z-index. The problem arises when I try to set the position of "inside" to absolute, as I am unable to assign a margin-bottom. A ...

issue with JavaScript canvas

My task is to develop a Blackberry application, but I have limited knowledge in Java. Since the application requires drawing capabilities, I decided to use HTML5 and JavaScript instead. I started reading some JavaScript tutorials to prepare for this proj ...

Stable header that jumps to the top when scrolled

I have implemented the JavaScript code below to set the header to a fixed position when it reaches the top of the page so that it remains visible while the user scrolls. Everything appears to be functional, but the header movement is abrupt and not smooth. ...