"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

Steps to enable ng-model input HTML in AngularJS

I am working on an HTML code snippet that includes a form input for audio link. However, when I try to enter a URL in the input field and submit the form, I encounter the following errors: <div class="inner-content-linkaudio"> <label for="linka ...

Can I find a better approach to optimize this code?

How can I refactor this code to move the entire DB query logic into a separate file and only call the function in this current file? passport.use( new GoogleStrategy({ clientID: googleId, clientSecret: clientSecret, callbackURL: ...

What is the best way to extract function bodies from a string with JavaScript?

I am currently searching for a solution to extract the body of a function declaration by its name from a JavaScript code string within a Node.js environment. Let's assume we have a file named spaghetti.js that can be read into a string. const allJs = ...

What is the purpose of re-checking the user in the passport.deserializeUser function?

After reading multiple articles on how to utilize passport.js, I'm left wondering why user verification is repeated within the passport.deserializeUser function. The code snippet looks like this: passport.deserializeUser((id, done) => { console. ...

Is it true that event.stopPropagation does not function for pseudoelements?

I am facing an issue with event handling in my ul element. The ul has three li children elements, and the ul itself has a useCapture event handler for click. In the click event handler, I successfully stop the event using event.stopPropagation(), and every ...

Prevent a specific folder from being included in expressjs routing

When using my expressjs app, I load public assets like this: app.use(express.static(__dirname + '/public')); Afterwards, I redirect all requests to the index, where every path is handled by Backbone app.get('*', routes.index); I am ...

What is the method for displaying an array separately for each item in JSON using JavaScript?

The issue arises when using for (let pet of person.pets) loop. In my JSON data, the "pets" field is an array but instead of getting a single array for each object, I am getting all pet arrays for every object in the JSON file. The desired outcome is to h ...

Maximum number of days that can be selected with Bootstrap Datepicker

I currently have a datepicker set with the multidate option and I am looking to specify a maximum number of days that users can select, say 5 days. Once a user has selected 5 days, any additional days should become disabled dynamically. How can this be a ...

Can someone please explain the distinction between $http.get() and axios.get() when used in vue.js?

I'm feeling a little bit puzzled trying to differentiate between $http.get() and axios.get(). I've searched through various sources but haven't found any answers that fully satisfy me. Can someone please offer some assistance? ...

Creating a POST request in Rails 3

Is there a way to integrate web services in Rails 3 by sending POST parameters to an external URL? Typically, I utilize a command line method like the one below for posting: curl -X POST -u "v10REVkw:XuCqIhyCw" \ -H "Content-Type: application/json" & ...

Send multipart form data to a different server via pipe

I need assistance with handling a POST request on my Node Express server for uploading images through multipart form data. Currently, my Express app is set up to use body parser which does not support multipart bodies and suggests using alternative librari ...

Modifying the attribute of an element inside an array

Presented below is an object: { "_id" : ObjectId("5a8d83d5d5048f1c9ae877a8"), "websites" : [ "", "", "" ], "keys" : [ { "_id" : ObjectId("5a8d83d5d5048f1c9ae877af"), "name ...

What is the best way to add a constant value to all objects within an array without having to iterate through each one

Is there a more concise way to add a fixed value to each object in an array without using a loop in JavaScript? Programming Language used: JavaScript Example Array: "cars": [ { "name":"Ford", "models":"Fiesta" }, { "name":"BMW", "models":"X1" }, ...

Tips for Emphasizing a Row in a Table Using a Specific Value

Currently, I am engaged in creating an educational YouTube tutorial that delves into Google App Script and Google Sheets. I have been attempting various methods to highlight a row containing the word "ABSENT", but all my endeavors have proven to be unsucc ...

The construction of the Gatsby site encountered a major obstacle

I've been facing challenges while trying to build my Gatsby site. Whenever I run 'gatsby develop' in the console, my app starts without any issues. However, when I attempt to build it, I encounter errors like the ones shown below. Does anyon ...

Steps for creating a basic table filter using jQuery

What is an efficient way to create a basic table filter using jQuery without pagination requirements? I want to retrieve data from a database and display it as a list. I would like to avoid using plugins and instead opt for concise code snippets. For ...

Getting URL parameters in NextJS when using Custom Document can be achieved by accessing the `ctx`

Currently, I am utilizing NextJS for generating SSR pages that are language-specific. I want to specify the lang property to indicate the language of the text. Here's what I have done so far: import Document, { Html, Head, Main, NextScript } from &qu ...

What is preventing me from accessing my session array in this.state.props from my mapStateToProps in React-Native Redux?

I am currently facing an issue with my Redux store setup. I am attempting to store an array of Session objects, where each Session object contains an array of Hand objects. However, when trying to access my store using `mapStateToProps`, none of the option ...

Exploring object key-value pairs using the 'for in' loop in JavaScript

Embarking on a project to develop a quiz in javascript, I am starting with an array that holds the questions as anonymous objects. var allQuestions = [{ "question": "Who was Luke's wingman in the battle at Hoth?", "choices": ["Dak", "Biggs", "Wedge", ...

Invoke the callback function before executing the next function

There is a function that calls an API: const response = fetch(APIfunctonName, { method: "POST", body: JSON.stringify(searchRequest), headers: { "Content-type": "application/json; charset=UTF-8", }, }) ...