What is the best way to fetch posts that contain an array of user IDs?

I've been working on implementing a bookmark feature for my website to allow users to save posts, but I'm encountering some issues.

The idea is that when a user clicks the bookmark button, their ID should be stored in the saves array. When trying to access saved posts, any post containing the user's ID in the saves array should be displayed.

However, I'm running into an error when fetching data from the frontend: "Cannot read properties of undefined (reading 'includes')."

It's worth noting that saves is defined as an array of user IDs in the schema.

Here is my controller.js function:

 const getSavedPosts = async(req, res) => {
 try {
     const userId = req.user._id;
     const post = await Post.find();
     const savedP = await post.saves.includes(userId);
     if(savedP){
     const userSavedPost = await Post.find({userId: {$in: savedP} })
        
         res.status(200).json(userSavedPost);
         console.log(userSavedPost)
         } else {
             return;
         }

     } catch (err) {
         res.status(500).json({ error: err.message });
     }
 };

And here is the PostModel.js:

import mongoose from "mongoose";
    
     const postSchema = mongoose.Schema({
         postedBy: {
             type: mongoose.Schema.Types.ObjectId,
             ref: 'User',
             required: true
         },
         text: {
             type: String,
             maxLength: 500
         },
         img: {
             type: String,
         },
         likes: {
             // array of users id's
             type: [mongoose.Schema.Types.ObjectId],
             ref: "User",
             default: []
         },
         saves: {
             // array of users id's
             type: [mongoose.Schema.Types.ObjectId],
             ref: "User",
             default: []
         },
         replies: [
             {
                 userId: {
                     type: mongoose.Schema.Types.ObjectId,
                     ref: 'User',
                     required: true
                 },
                 text: {
                     type: String,
                     required: true
                 },
                 userProfilePic: {
                     type: String,
                 },
                 username: {
                     type: String
                 }
             }
         ]
     }, {timestamps: true}
     )
    
     const Post = mongoose.model('Post', postSchema);
    
     export default Post;

Answer №1

You've made a promising start, but there are several issues with your code that need to be addressed. To simplify things, I'll provide you with a solution along with some explanatory notes.

To enhance your postSchema, make sure the likes and saves properties are defined as shown below:

//...

likes: [{
   type: mongoose.Schema.Types.ObjectId,
   ref: "User",
   default: []
}],
saves: [{
   type: mongoose.Schema.Types.ObjectId,
   ref: "User",
   default: []
}],

//...

Update your getSavedPosts function with the following modifications:

const getSavedPosts = async(req, res) => {
   try {
      // Verify that req.user contains the necessary data
      console.log('req.user=', req.user);
      const userId = req.user._id;
      // Search for posts associated with the user's saves array
      const userSavedPost = await Post.find({saves: userId });
      // Check if any posts were found
      if(userSavedPost.length){
         console.log(userSavedPost);
         return res.status(200).json({
            posts: userSavedPost
         });
      }else{
         return res.status(200).json({
            message: 'No posts found'
         });
      }  
   } catch(err) {
      // Log the error without revealing sensitive information
      console.log(err);
      res.status(500).json({ 
         message: 'Error on server' 
      });
   }
};

Answer №2

Could it be possible that the variable post is being returned as an array?

In that case, perhaps you could consider iterating through each of its elements?

For instance:

const savedP = post.filter((singlePost) => singlePost.saves.includes(userId));

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

Looking to install nodemon for Node.js on macOS? If you're encountering a "command not found" error, here's

After installing nodemon using the command npm install -g nodemon, I encountered a Permissions issue. To resolve this, I used the sudo npm install -g nodemon command. However, when attempting to run the "nodeman" command, I kept receiving an error that s ...

Exploring Node troubleshooting with WebPack and Feathers

Currently, I am part of a team working on a project that involves using Node, Webpack, TypeScript, and Express/Feathers. While my fellow developers are experienced in these technologies, I have limited experience with JavaScript mainly on the client-side a ...

Unable to modify the model of the directive

I'm facing an issue where additional elements added to my array within a controller of a directive are not being displayed in the view. What's even more frustrating is that when I print my model, it doesn't reflect the new elements that have ...

Recover Your Password Using Node.js

Currently, I am working on implementing a reset password feature. Users are required to enter their username, email, and full name. If these values match the data in the database, the password is changed. Otherwise, an error message is displayed. Here is t ...

What causes objects to be added to an array even when the condition is not met?

In the process of creating a terminal game using node.js, I am developing a random field consisting of different elements such as hats, holes, and pathways. The player's objective is to navigate through the maze and locate their hat within the field. ...

The issue of Ng-Route not functioning properly on a Node/Express static server

I need assistance with my app.js file that currently directs all requests to pages/index.html. Now I am attempting to utilize Angular to route user requests for '/#/media' by adding the following code: academy.config(function($routeProvider) { ...

Difficulty arises when attempting to run code when a checkbox is not selected

In my form validation process, I am facing an issue where I need to validate certain values only if a checkbox is unchecked. If the checkbox is checked, I want to use the values that were previously added. However, none of the existing code snippets seem t ...

The controller is unable to retrieve the posted value

Whenever I try to retrieve the post value from my controller, it always returns null. Even though I can see that there is a post value present when I check, for some reason, I am not able to access that value in my controller. Does anyone know what the p ...

Time well spent with The Mighty Ajax

Within the success function for my post, I need to include the time posted. The original PHP code snippet that displays the time looks like this: echo "<br/><a href='#' class='subtleLink' style='font-weight:normal;'& ...

Is there a way to continuously switch a CSS animation class without needing a second click?

I am seeking a solution to animate the color and size of a div box, then return it to its original state when a button is clicked. Here is an example of my code: document.getElementById("andAction").addEventListener("click", function() { document.getE ...

The redirect function failed to take me to the necessary page (/SignIn), instead it kept me on the current page but with a different URL (/updateinfo?)

After updating the user's information, I expected the window.location method to redirect me to the sign-in page. However, the redirection is not working as intended. Instead, it redirects me to the same page (/updateinfo) but with a changed URL (/upda ...

Utilizing attributes as scope properties within AngularJS

I am currently working on a directive and I need to pass the Attributes (Attrs) to the $scope, however, I am facing some difficulties in achieving this. Specifically, my goal is to assign attributes in my template based on the name set in my date-picker ta ...

Horizontal Panning Feature for D3 Horizontal Bar Charts

I am working on a D3 Bar Chart and I would like it to have horizontal panning functionality similar to this example: https://jsfiddle.net/Cayman/vpn8mz4g/1/. However, I am facing an overflow issue on the left side that I need to resolve. Below is the CSV ...

Safari having trouble with cross-domain cookie functionality

I currently manage 2 different websites: 3rdpartycookiemanager.com website.com When I access website: I initiate an Ajax call to: using the following jQuery call: $.ajax({ ... type: 'POST', url: 'https://www.3rdpartycookiemanag ...

Error: The term "require" is not recognized in the context of the React

After creating my own React component as an NPM package and publishing it on NPM, I encountered an error when trying to import and use it in other Create React App (CRA) projects. The error occurs when running npm start in the command line. See the screens ...

Looking to utilize Python Selenium for downloading a PDF file

I am currently working on automating the process of downloading PDFs using Selenium Webdriver in Python An issue I've encountered is that the download button is hidden within an embed tag in the HTML code <embed width="100%" height="100%" name="p ...

What could be causing the header of the datatable to be out of alignment with the rest of

I'm facing an issue with my datatable where the header is misaligned with the content. Can someone please assist me in adjusting the header and content so that they are parallel? It doesn't look right at the moment. <div style="margin-top:1 ...

Storing toggle open state using a variable

I have created a toggle open/close DIV with a UL list inside that looks like this: <div id="dropdown-1"> <div class="option-heading"> <i class="fa fa-angle-double-up"></i> <i class ...

Leveraging AngularJS directives and $scope autonomously

Let me provide some context first: Previously, my focus was on developing lightweight, single-page Angular applications. However, in the past few days, I began working on a new project that combines Tapestry and Backbone. It has proven to be quite overwhe ...

Issues with displaying public images in Next.js production build are being reported

My Next.js app is deployed on Heroku. Images show up when I develop locally, but once pushed to Heroku and checked on the live site, the images return a 404 error. The images (.png) are stored in a public folder within my project, and I reference them in t ...