"Upon populating an object with Mongoose, the return value is an

Recently, I set up a mongo database and created a Post model that has a reference to the User by _id. I wanted to retrieve information about the posts a user has made, so I implemented a callback function within exec() while populating the selected User. However, the result turned out to be an empty array.

{
  posts: [  {
    _id: 5f287dd39eb82544302b974b,
    title: 'It;s a good day pt.3',
    content: 'Sunny on the morning and little cloudy in the evening :)',
    __v: 0
  }
],
  _id: 5f287adf86b8a617300122a7,
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa8a5a88aada7aba3a6e4a9a5a7">[email protected]</a>',
  name: 'Bob',
  __v: 2
}

Unfortunately, the actual outcome is as follows:

{
  posts: [],
  _id: 5f287adf86b8a617300122a7,
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1838e83a1868c80888dcf828e8c">[email protected]</a>',
  name: 'Bob',
  __v: 2
}

I would be grateful for any assistance in resolving this issue. Here is the JavaScript code snippet:

let mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/blog_demo_2", {useNewUrlParser: true, useUnifiedTopology: true});

let postSchema = new mongoose.Schema({
    title: String,
    content: String
});
let Post = mongoose.model("Post", postSchema);

let userSchema = new mongoose.Schema({
    email: String,
    name: String,
    posts: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Post'
    }]
});
let User = mongoose.model("User", userSchema);

User.create({
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0929f92b0979d91999cde939f9d">[email protected]</a>",
    name: "Bob"
});

Post.create({
    title: "It's a good day pt.3",
    content: "Sunny on the morning and little cloudy in the evening :)"
}, function (err, newlyPost) {
    if(err){
        console.log(err);
    }else{
        User.findOne({email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5855587a5d575b535614595557">[email protected]</a>"}, function (err, foundUser) {
            if(err){
                console.log(err);
            }else{
                foundUser.posts.push(newlyPost);
                foundUser.save();
            }
        })
    }
});

User.findOne({email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="65070a07250208040c094b060a08">[email protected]</a>"}).populate("posts").exec(function (err, user) {
    if(err){
        console.log(err);
    }else{
        console.log(user);
    }
});

Answer №1

You've got

   posts: [{
        type: mongoose.Schema.Types.ObjectId,
        connectedTo: 'Post'
    }]

Make sure to use connectedTo instead of rel

   posts: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Post'
    }]

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

Bi-weekly Calendar Gathering

I am able to get my events sorted by day with the following code: daysOfWeek: [2], However, I have not been able to find any information in the documentation on how to make it sort fortnightly. Can this be done with fullcalendar? Solution: Just a heads ...

Executing a cURL request using Node.js

Looking for assistance in converting the request below: curl -F <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a777f7e737b275a73777b7d7f34706a7d">[email protected]</a> <url> to an axios request if possible. ...

Storing the value from the INPUT field in the state of React is not permitted

I'm attempting to retrieve the user input value from the INPUT field and update it in the corresponding state. However, no matter what I type in the field, it doesn't get set to the state. createForm(x){ var dx = 'd'+x let da ...

java code unicode feature in csharp

Here's the code I am using: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); The 'title' property contains values en ...

The installation of npm modules is failing with the error message: "'react-scripts' is not recognized as a valid command, internally or externally."

As I revisited my old project on GitHub, things were running smoothly a few months prior. However, upon attempting to npm install, I noticed the presence of the node modules folder and encountered some npm errors. https://i.stack.imgur.com/awvjt.png Sub ...

"What is the best way to calculate a percentage using a field from one collection and a populated field from another collection in

In my collection, I have a field with numbers and populated ObjectId inside that collection where there is another field with numbers. The structure looks like this: {"_id":"5abe65e298002b2334bb1470","electoralUnit":"5ab906612f30fe23dc592591","turnoutByHo ...

Is it possible to use header() function in a file that is being accessed through

In a specific package, there is a crucial file that verifies session data and redirects the user to the login page with an error message if no valid session exists, using header("Location:" . $var);. This particular file is included in almost all files wi ...

The JavaScript array remains unaltered

I've got an express server set up with GET and POST routes. The initial state looks something like this: let orders = [ { sum: 0, purchases: [ { id: 1, contractId: ...

Glowing effects on svg shapes

I'm looking to add a pulsing light animation around an SVG half circle shape that I have created. After experimenting with CSS and Webkit, the closest I've come is achieving a pulsing light around the parent element, rather than the actual shape ...

What is the best way to display or conceal an array object using a toggle switch?

I'm trying to implement a show/hide functionality for descriptions when toggling the switch. Additionally, I want the switch to be initially checked and only show the description of each respective result. However, my current code is displaying all de ...

ReactJS Chatkit has not been initialized

I made some progress on a tutorial for creating an Instant Messenger application using React and Chatkit. The tutorial can be found in the link below: https://www.youtube.com/watch?v=6vcIW0CO07k However, I hit a roadblock around the 19-minute mark. In t ...

Is there a more efficient approach to extracting the border width using javascript?

I implemented the following code: const playGard = document.getElementsByClassName("playGard")[0]; const borderW = getComputedStyle(playGard,null).getPropertyValue('border-left-width').substr(0,2); The result I obtained was "10". Is there a m ...

Do not continue submitting if the innerHTML matches the specified value

I am currently working on a web page that verifies if an email entered by the user is available in the database. If it is, I need to prevent the form from being submitted. To achieve this, I have implemented Ajax for real-time checking of the email and di ...

Using default JavaScriptSerializer to bind DateTime to knockout view model

Recently, I started using knockout and encountered a problem with DateTime Serialization and Deserialization when using the JavaScriptSerializer. I modified the gifts model in Steve's koListEditor example from his blog to include a new field for Modi ...

How can I access the rendered HTML element from a component in Vue 3?

This particular component is known as LayerComponent (placeholder). <script> export default { data() { return { count: 0 } } } </script> <template> <button @click="count++">You have clicked me {{ count ...

Encountering an issue while attempting to run a Node.js server on a Mac, receiving the error message "no appropriate image located."

unknown406c8f2d5ecb:proves airrider3$ node tronServer.js [Error: dlopen(/Users/airrider3/Documents/proves/node_modules/now/node_modules/node-proxy/build/Release/nodeproxy.node, 1): no suitable image found. Did find: /Users/airrider3/Documents/proves/n ...

Transforming an interactive HTML webpage into React/JSX

Imagine a scenario where I have two files: example.html <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="u ...

Mobile Devices and Local Storage: What You Need to Know for Safe and Efficient Use. Looking for advice from experienced developers

Need help with caching user input on an Angular11 + Firebase app? Let's discuss implementing a caching feature for a dynamic form section that can contain varying fields based on the use case. The goal is to save user input in LocalStorage to ensure ...

What distinguishes node from node js?

Following the instructions on https://nodejs.org/en/download/package-manager/, I installed Node.js. Upon checking the current version using: :~/Downloads$ nodejs -v I discovered that I was running v4.2.6, which is an older version. Deciding to update, I ...

Guide on implementing jQuery Validation plugin with server-side validation at the form level

Does anyone have a suggestion for how to handle server-side validation errors that occur after passing the initial client-side validation on a form? $("#contact_form").validate({ submitHandler: function(form) { $.ajax({ type: 'POST', ...