What is causing the issue with mongoose populate not working when trying to populate an array?

My database setup includes 2 schemas:

const mongoose = require('mongoose');

const PinSchema = new mongoose.Schema({
  title: String,
  content: String,
  image: String,
  latitude: Number,
  longitude: Number,
  author: {
    type: mongoose.Schema.ObjectId,
    ref: "User"
  },
  comments: [
    {
      text: String,
      createdAt: {
        type: Date,
        default: Date.now,
        author: {
          type: mongoose.Schema.ObjectId,
          ref: "User"
        }
      }
    }
  ]
}, { timestamps: true });

module.exports = mongoose.model("Pin", PinSchema);

and

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  picture: String
});

module.exports = mongoose.model("User", UserSchema);

In the Pin schema, the author field is linked to the _id in the User schema.

When trying to populate the comments' author field in the Pin schema like this:

const pinUpdated = await Pin.findOneAndUpdate(
        { _id: pinId },
        { $push: { comments: "some comment" } },
        { new: true }
      ).populate("author")
       .populate("comments.author");

the author field in the result object turns out to be null, indicating that the population did not work as expected.

Using the native mongo syntax with $lookup may be an alternative, but in this case, it involves looking up a field in an array of objects:

db.pins.aggregate([
    {
   $lookup:
     {
       from: "users",
       localField: "comments._id", // this won't work
       foreignField: "_id",
       as: "authorOutput"
     }
}    
])

What could be missing in the populate() method that is causing this issue?

Answer №1

It appears that the author field within the comments array is mistakenly nested inside the createdAt object. To correct this, you can adjust the PinSchema as shown below (closing curly brace before author):

const PinSchema = new mongoose.Schema({
  ...
  comments: [
    {
      text: String,
      createdAt: {
        type: Date,
        default: Date.now,
      },
      author: {
          type: mongoose.Schema.ObjectId,
          ref: "User"
      }
    }
  ]
}, { timestamps: true });

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

Is your $http request causing an XML parsing issue?

I'm attempting to utilize the $HTTP method from angularJS to access my restful web service. On entering my web service URL in the browser, I receive a result of APPLICATION/JSON type. {"id":20418,"content":"Hello, World!"} The URL for my web servic ...

Displaying JSON data in HTML proves to be a challenge

I have collected JSON data and organized it into two arrays, then displayed it in JSON format. Now I'm trying to showcase this data in HTML using two loops by correlating the IDs of one array with the userIds of another array. {"personaldetails":[{"i ...

There appears to be a syntax error in the Values section of the .env file when using nodejs

I have been working on implementing nodemailer for a contact form. After researching several resources, I came across the following code snippet in server.js: // require('dotenv').config(); require('dotenv').config({ path: require(&apos ...

Acquire a structured list of the focus order within the DOM elements

It intrigues me how the DOM is constantly changing. I'm curious if there's an easy way to retrieve a sorted list of focusable elements within the DOM at any moment. This would encompass nodes with a specified tabindex value that isn't -1, as ...

Transforming a group of JSON objects into a two-dimensional array

Below is an array of JSON objects: var data = [{ 1: { name: 'Name 1', id: 'one' } }, { 2: { name: 'Name 2', id: 'two' } }]; I want to transform this into a 2-D array like this: var newData ...

Stop the sudden jump when following a hashed link using jQuery

Below is the code snippet I am working with: $( document ).ready(function() { $( '.prevent-default' ).click(function( event ) { event.preventDefault(); }); }); To prevent the window from jumping when a hashed anchor ...

Is it possible to generate a specified number of divs or HTML tags with varying information using ReactJS?

Currently, I am in the process of constructing this website and I have noticed that I have 4 divs that are essentially doing the same thing. However, I find myself copying and pasting these divs 4 times, only making minor changes to 4 bits of information. ...

Developing a Multi-Stage Pop-Up with Jquery

I am interested in creating a custom multi-step modal This particular div has dynamically generated classes $('.modal-content').append('<div class="modal-body step step-' + key + '" data-step="'+key+'"></div> ...

Getting data from components in React: A step-by-step guide

As a newcomer to Reactjs, I find myself working on an existing project where I am attempting to retrieve product reviews using components. However, my console currently displays 0 reviews. How can I resolve this issue? The file in question is "pages/[slug ...

How to customize TextField error color in Material-UI using conditional logic in React

Currently, I am incorporating the React Material-UI library into my project and faced with a challenge of conditionally changing the error color of a TextField. My goal is to alter the color of the helper text, border, text, and required marker to yellow ...

What is the best method to iterate through a jQuery array variable without any errors?

I am struggling with a PHP project where I need to create a json array of data values that will be used in a jQuery script. The array looks something like this: [3,94,83,141]. My goal is to leverage these values to manipulate the visibility of rows in a ta ...

Network-wide posting of Mongoose Schema

I am faced with a situation where I have two Node.js applications both utilizing Mongoose, but on separate machines. The first machine hosts a MongoDB database which the second machine connects to in order to add documents at certain intervals. What I am c ...

Insert JavaScript into this HTML document

I am looking to integrate the "TimeCircles JavaScript library into my project, but I am facing some challenges in doing it correctly. I plan to include the necessary files at the following location: /js/count-down/timecircles.css and /js/count-down/timecir ...

Identifying a failed Ajax Request in JavaScript

How can I check if an Ajax request failed to load a file? Here is the code I'm currently using: var pro = undefined; var xmlhttp; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTT ...

Embarking on the GSAP journey

I'm attempting my first animation using GSAP, but no matter what I try, nothing seems to be working. I've even tried using example code without success. Within my PHP file, I have the following code snippet: <head> <script src="https:/ ...

Deactivate "When the viewModel attribute holds the phrase 'some text'"

I came across this answer on Stack Overflow regarding checking for a value in Knockout, but it seems to be outdated. I am attempting to achieve something like this: <li> <span data-bind="text: Subject"></span> <!-- ko if: Subjec ...

Getting started with `sessionStorage` in a React application

Currently, I am attempting to save an item in sessionStorage prior to rendering. The code snippet I have looks like this: componentWillMount() { sessionStorage.setItem("isUserLogged", false); } However, I encountered an error stating th ...

There seems to be an issue with Node.js/Express: the page at /

Recently, I've been working on some code (specifically in app.js on the server). console.log("Server started. If you're reading this then your computer is still alive."); //Just a test command to ensure everything is functioning correctly. var ...

Always ensure that an element remains at the bottom during the sorting process

Currently, I have a list of items with an integer attribute that aids in sorting the list. However, I am looking for a way to designate specific items to always appear at the bottom of the list regardless of the sorting criteria. Is there a singular valu ...

Revamping repetitive JavaScript code for the pagination of Instagram Stories

I'm currently developing a website that utilizes fullpage.js and includes a section with multiple slides. These slides automatically transition every 10 seconds. I wanted to implement progress bars similar to those on Instagram, where each bar fills ...