Combining queries in mongodb with nested joins

I'm attempting to retrieve a structure where I first populate content, and within content there is an array field named comments. From comments, I aim to populate user.

Below is the schema:

const contentScheme = new Schema({
    post_id:  { type: Number },
    post_type:  { type: String },
    likes_count:  { type: String },
    likes_by: [{type: Schema.Types.ObjectId, ref: 'User'}],
    comments_count:{ type: Number },
    comments:[{type: Schema.Types.ObjectId, ref: 'Comment'}],
},{timestamps : true});


const commentScheme = new Schema({
    created_by: { type: Schema.Types.ObjectId, ref: 'User' },
    post_id:  { type: String },
    post_type:  { type: String },
    comment:  { type: String },
    reply_to:  { type: Number },
    pinned:{ type: Number },
  
},{timestamps : true});

const userSchema = new Schema({
    email: { type: String, required: true,  index: { unique: true } },
    avatar: { type: String },
    token: { type: String },
    display_name: { type: String , required: true},
    last_updated: {
        type: Date,
        default: Date.now
      }

});

Here is my current approach:

ContentModel.findOne({
                        post_id:args.post_id,post_type:args.post_type},(err,rslt)=>{
                        if(err){ 
                            reject(err);
                        }
                        else {
                           console.log(rslt)
                            resolve(rslt);
                        }
                    }).populate("comments").populate({ path: 'comments.created_by', model: UserModel })

Here is the result from the above query:

{
  _id: new ObjectId("618cdecbf1551c02355e4e6a"),
  post_id: 1,
  post_type: 'note',
  likes_count: '1',
  likes_by: [
    new ObjectId("6187bbe0e4d3a0aa98fd0cc6"),
    new ObjectId("6187bbe0e4d3a0aa98fd0cc6"),
    new ObjectId("6187bbe0e4d3a0aa98fd0cc6"),
    new ObjectId("6187bed3e4d3a0aa98fd0cc9")
  ],
  comments_count: 4,
  comments: [
    {
      _id: new ObjectId("618dced6ee441fca8e4e1659"),
      created_by: new ObjectId("6187bbe0e4d3a0aa98fd0cc6"),
      post_id: '1',
      post_type: 'note',
      comment: 'INI COMMENT',
      reply_to: null,
      pinned: 0,
      replies: [],
      createdAt: 2021-11-12T02:17:58.464Z,
      updatedAt: 2021-11-12T02:17:58.464Z,
      __v: 0
    },
    {
      _id: new ObjectId("618dd2281c5f1ddc6589728d"),
      created_by: new ObjectId("6187bed3e4d3a0aa98fd0cc9"),
      post_id: '1',
      post_type: 'note',
      comment: 'TEST COMMENT MEMBER',
      reply_to: null,
      pinned: 0,
      replies: [],
      createdAt: 2021-11-12T02:32:08.092Z,
      updatedAt: 2021-11-12T02:32:08.092Z,
      __v: 0
    }
  ],
  createdAt: 2021-11-11T09:13:47.412Z,
  updatedAt: 2021-11-12T02:32:08.212Z,
  __v: 0
}

At comments.created_by, the result still displays an object id instead of the user object. How can I resolve this?

Answer №1

Experience the benefits of delving into multiple layers at once

ContentModel.findOne().populate({ path:'comments', populate: {
   path: 'created_by',
   model: 'UserModel'
}})

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

Transferring items between different containers without using innerHTML

I've got an embedded <ul> within a (hidden) <aside id="idDetails">. How can I move the ul element from inside the aside and position it in a <div id="projectSide"> without using innerHTML? Any solutions in both plain JavaScript and j ...

.click function failing to trigger on dynamically loaded form

I'm facing an issue with a form that displays images from my database. After retrieving the filepaths, they are loaded dynamically into the form along with a "Delete" <button> for users to delete the image via AJAX. Although I can successfully ...

Tips for refreshing the page upon Geolocation request

I am working on a HTML5 project that requests geolocation from the user. Here is an image of what it looks like: https://i.sstatic.net/o6yCj.png My main query is: Is there a way to refresh the page automatically once the user grants permission to share t ...

Rendering React on the server side while making requests to the backend

I am currently working on a React application with server-side rendering using Express. In my implementation, I have a straightforward App component: import React, { Component } from 'react'; export default class App extends Component { const ...

Navigate through chosen options by clicking on a button

It's a new day and I'm facing a simple challenge that seems complicated in the morning haze. I need to create a select dropdown with zoom percentage values, along with + and - buttons to navigate through the list. If I have the following setup: ...

Is there a way to prevent users from right clicking on all links with the same class using js/jquery?

Rails 4 + JS + jquery Is there a way to disable right click on links with the same class in Rails? <% @schedule_hash.values.each do |schedule| %> <%= link_to "Cancellation policy", {:controller => 'web', :action => 'get ...

The function window.scrollBy seems to be causing a conflict with jjmslideshow, resulting in the page being unable to

I wrote a simple script to create a "smooth scroll" effect when a specific link is clicked: (function() { 'use strict'; // Checking for compatibility if ( 'querySelector' in document && 'addEventListener' in window ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...

Failure to trigger a follow-up function in webSQL transaction's success callback

Review the code below. I have called setQuestion() within the successCallBack of db.transaction but am encountering an error: Uncaught TypeError: this.setQuestions is not a function. Can you spot any issues in my code? game.module( "game.scenes.scene" ) ...

Utilize JavaScript to load external JavaScript libraries and scripts

Currently, I am working on developing a console application using JavaScript/Node.js. However, when compiling the script.js file, I encounter a ReferenceError: $ is not defined issue. //user input from command line var readline = require('readline&ap ...

Odd behavior of the "for in" loop in Node.js

It seems like I'm struggling with the use of the "for in" statement. When working with a JSON document retrieved from a mongodb query (using nodejs + mongoose), its structure looks something like this: [{ "_id":"596f2f2ffbf8ab12bc8e5ee7", "da ...

Enhance user experience with Bootstrap by automatically adding a frame around a card upon clicking

Hello everyone! I am a beginner in the Angular/Web Development world and I am currently working on improving my HTML/CSS skills. While using Bootstrap in my Angular project, I ran into a challenge that I couldn't figure out on my own. I have implement ...

What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below: class Sup { static member: any; static log() { console.log('sup'); } } If you write the following code: let x = Sup; Why does the type of x show up as typeof Sup (hig ...

Encountering an issue with the mongo command following the installation of MongoDB version 3.6.3

After successfully installing MongoDB version 3.6.3, I encountered issues when trying to run the Mongo command. Upon running the command, I received the following error message: MongoDB shell version v3.6.3 connecting to: mongodb://127.0.0.1:27017 ...

Extract the canvas code line from a function without using the eval function

Greetings, fellow Stackers! Please pardon my formatting as this is my debut question on this platform. I am currently working on a basic vector drawing tool. If you want to view the full CodePen code for reference, feel free to click here. Here's t ...

Ways to send a POST variable to PHP without refreshing the webpage

Is there a way to pass a simple variable from a text-box on a different page to PHP without reloading it? I've been informed that Ajax is required for this task, but I'm unsure of how to go about implementing it. Can someone provide me with a sam ...

Determining the Maximum Number of Characters Allowed in a Div Using jQuery

Could anyone provide guidance on how to populate a div with single characters? I want the div to span the width of the viewport. The code to get the width is: $(window).width(); I would like JavaScript to generate HTML similar to this: <div id="text ...

Using JavaScript to implement CSS3 with multiple background images

Is there a way to programmatically define multiple background images in CSS3 using JavaScript? While the common approach would be: var element = document.createElement( 'div' ); element.style.backgroundImage = "url('a.png') 0 100%, ur ...

What is the best method for incorporating jQuery code into a separate file within a WordPress theme?

I'm fairly new to working with Javascript/jQuery, so please be patient with me. Currently, I'm in the process of creating a custom WordPress theme where I've been using jQuery to modify the main navigation menu generated in my header file ( ...

What steps do I need to take to create npm packages specifically for react-native development?

Which programming languages are essential for creating npm packages that work on both android and ios platforms in react-native development? Can you suggest any helpful documentation or blogs for developing npm packages that support ...