Using Mongoose Populate to retrieve all user posts results in an array with no content

I am delving into Express.js to enhance my understanding and attempting to develop a basic blogging platform.

The user model I have devised is quite straightforward: it includes fields for Username, Display Name, and an array of posts.

const userSchema = new Schema({
    username: {
        type: String,
        required: true, 
        unique: true, 
        trim: true, 
        minlength: 3
    },
    displayname: {
        type: String,
        required: true,
        minlength: 1
    },
    posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
}, {
    timestamps: true,
});

Similarly, the Post model consists of content and author information.

const postSchema = new Schema({
    body: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 140
    },
    author: { type: Schema.Types.ObjectId, ref: 'User', required: true }
});

I have successfully created a new user alongside a post:

[
  {
    "posts": [],
    "_id": "5d32c9474e28f66c08119198",
    "username": "Prince",
    "displayname": "The Artist",
    "createdAt": "2019-07-20T07:56:55.405Z",
    "updatedAt": "2019-07-20T07:56:55.405Z",
    "__v": 0
  }
]

[
  {
    "_id": "5d34af1ecae7e41a40b46b5a",
    "body": "This is my first post.",
    "author": "5d32c9474e28f66c08119198",
    "__v": 0
  }
]

Below are the routes for creating a user and a post:

//Create a user
router.route('/create').post((req, res) => {
    const username = req.body.username;
    const displayname = req.body.displayname;

    const newUser = new User({
        username, 
        displayname
    });

    newUser.save()
        .then(() => res.json('New user created!'))
        .catch(err => res.status(400).json(`Error: ${err}`));
});
//Create A Post
router.route('/create').post((req, res) => {
    const body = req.body.body;
    const author = req.body.author;
    const newPost = new Post({
        body,
        author
    });

    newPost.save()
        .then(() => res.json('Created new post!'))
        .catch(err => res.status(400).json(`Error: ${err}`));
});

In addition, here's how I retrieve all posts by a specific user:

//Get all posts by user
router.route('/posts/:id').get((req, res) => {
    User.findById(req.params.id)
        .populate('posts')
        .exec((err, user) => {
            if(err) {
                res.status(400).json(`Error: ${err}`);
            } else {
                res.json(user.posts);
            }
        });
});

Upon inspecting the response from /users/posts/:id, I notice that the array is empty even though I anticipated it to contain the posts authored by the specified ID. Could there be a misunderstanding on my part regarding how the populate function operates?

Answer №1

To ensure mongoose's populate function works correctly, make sure to include the post id in the user's post list.

router.post('/create' async (req, res) => {
    const body = req.body.body;
    const author = req.body.author;
    const newPost = new Post({
        body,
        author
    });
    try {
        const user = await User.findById(author);
        const post = await newPost.save()
        user.posts = user.posts.concat(post._id)
        await user.save()
        return res.json(post.toJSON())
    } catch (e) {
        return res.status(400).json(`Error: ${e}`));
    }
});

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

AngularJS JSON Array

I have an array containing multiple objects in JSON, as well as a select element that contains an array. Depending on the selection made in the first array, another select box will be dynamically loaded right below it. HTML Code <div class="list"> ...

Looking to minify a JavaScript file? Consider changing the overly long variable name "veryLoooooooongVariable" to something shorter,

When working on improving readability, I tend to use very long variable names which can increase the size of my JS files. I'm wondering if there are any tools or libraries available that can automatically change these long names to shorter ones? I am ...

In MongoDB, the result is grouped as key-value pairs

Before reaching the $group stage in the pipeline, the document was computed as follows: cycle_id | entity1 | entity 2 1 | 0 | 1 1 | 1 | 5 2 | 0 | 3 The grouping was done using the script below: { &q ...

Remove the attribute from the element in the ng-repeat loop

Here is my ng-repeat code snippet: <th ng-repeat="field in tableFields" translate="{{field.headerTitle | translate}}" ts-criteria="{{field.sortable ? field.fieldKey : null}}"> <label class="i-checks" ng-if="field.isCheckbox"> & ...

Is it possible to use the .focus() event on an entire form in JQuery? If so, how

Take a look at this HTML snippet: <form ....> <textarea>....</textarea <input .... /> </form> I'm trying to set up a help section that appears when the user focuses on any form element, and disappears when they lose ...

The art of proper data modeling in MongoDB

As a MongoDB newbie, I'm figuring out how to handle a collection that stores user data including names and roles. Each user can have one of three roles: admin, user, or guest. Typically in a relational database, I would maintain two tables - one for u ...

Updating the User Interface in ReactJS based on changes in the state

I am relatively new to ReactJS and I am currently working on building a Sudoku Solver. My goal is to update the state in real-time so that the user can visually see how the algorithm is progressing. However, my current code only updates the UI at the end ...

The requested data at http://localhost:3000/getalldata/undefined was not found, resulting in a 404

Having trouble fetching data from backend to frontend, unsure of where the error lies. Please assist in resolving the issue. Feel free to ask if you have any questions. https://i.sstatic.net/JWhsf.png https://i.sstatic.net/ewCTd.png https://i.sstatic.ne ...

Leveraging jQuery data to handle RESTful requests

I am currently working on filtering the request response based on the status code that is returned. I have figured out how to retrieve the status code using the "complete" statement, but I am unsure about how to access the data handler. My goal is to inc ...

Simultaneous activation of two click events in Javascript

I am looking to create a game using JavaScript. The game will be designed for two players to play on the same mobile device. I am facing a challenge with coordinating the players' clicks, as they may happen simultaneously. I have attempted to use bot ...

Tips on how to display a gif image during the loading of ajax content using JavaScript

Currently, I am attempting to load a gif image while waiting for the AJAX data to be loaded and displayed. However, I am struggling with this task. I would appreciate any assistance on how to implement a loading gif in my code for the advanced search feat ...

Steps to load a script when the document is ready:

What is the best method to include JavaScript using the following code: <script type="text/javascript" src="http://uads.ir/l.php?s=125125&w=5307cd5c027373e1773c9869"></script> only after the page has fully loaded? $(document).ready(funct ...

Expanding an HTML table with a click: A step-by-step guide

I have successfully generated an HTML table using JavaScript. However, I now need to display additional data in a row by expanding it on click. Table functionality: The table is populated with brands and their respective items. When a brand is clicked, ...

Fetching post data from an HTML form in Node.js using Express 4: A comprehensive guide

This is the content of my main.js file: var express = require("express"); var app = express(); var bodyParser = require("body-parser"); var userAPI = express.Router(); app.use(express.static(__dirname + '/public')); app.use( bodyParser.json() ) ...

Merge JavaScript files from various folders using grunt's configuration settings

I am currently working with Grunt and Sass, and I am in search of a SASS-like feature that will allow me to import any JavaScript file I desire and merge them into a single file based on some configuration depending on the directory I am in. For instance, ...

The position of a jQuery element gets reset when both the show and stop animations are used

When I use jQuery's .position() to place an element, everything works fine. But as soon as I display an animation and then cancel it with an ajax call, the position of the element resets. function displayMessage(msg) { var $messageEl = $('#u ...

Changing Mongo Shell $or to PHP SyntaxLet's translate the $or

Seeking help as a newcomer, I am trying to convert this robomongo query into a mongolid query: db.getCollection('products').find({'images':{$size:0}, $or: ...

What is the optimal configuration for a node.js stack serving a high-traffic application?

Currently, I am working on a Node.js stack application being used by a large user base of over 25000 individuals. Our technology stack includes the Sails.js framework and MongoDB. The application is hosted on an EC2 instance with 30GB of RAM, and the datab ...

Finding compatibility between two arrays with flexibility

I am currently working on an Ionic app that involves an array of ingredients and a service with recipes. You can find the structure of the recipe service here. My goal is to match the ingredients with the recipes. Currently, I have implemented the followi ...

Templating with Underscores: Revolutionizing token markers

When using out of the box underscore templating, the default markers for raw content are <%= %>, and for HTML escaped content are <%- %>. However, it is possible to change these markers by adjusting the template settings, for example: _.templ ...