What is the best way to locate posts from authors who are already part of the friends array?

I'm currently working on a task where I need to retrieve all posts from the friends list of a user and display them in descending order based on creation date.

Below is the controller function responsible for fetching all posts from friends:

async function indexByFriends(req, res) {
  const { handle } = req.user;
  console.log('handle:', handle);
  try {
    const userProfile = await Profile.findOne({ handle });
    console.log('friends handles:', userProfile.friends);

    const posts = await Post.find({ author: { $in: userProfile.friends } })
      .sort({ createdAt: -1 })
      .populate({
        path: 'author',
        select: '-_id -__v',
        match: { handle: { $in: userProfile.friends } }
      });

    res.json(posts);
  } catch (err) {
    console.error(err);
    res.status(500).json(err);
  }
}

Here is the Profile model:

import mongoose from 'mongoose'

const Schema = mongoose.Schema

const profileSchema = new Schema({
  // Profile schema details here
}, {
  timestamps: true,
})

const Profile = mongoose.model('Profile', profileSchema)

export { Profile }

And the Post model:

import mongoose from 'mongoose'

const Schema = mongoose.Schema

const postSchema = new Schema({
  // Post schema details here
},{
  timestamps: true,
})

const Post = mongoose.model('Post', postSchema)

export { Post }

However, when I execute the function, I encounter a 500 error:

GET /api/posts/friends 500 131.701 ms - 258
along with
CastError: Cast to ObjectId failed for value "SBBGameMaster" (type string) at path "_id" for model "Profile"

The JSON data returned looks like this:

{
    // JSON data details here
}

It seems the issue revolves around using the handle instead of the object_id. I prefer using the handle for easier user lookup instead of having to rely on the user's _id.

My expectation is to display a list of posts where the author's handle matches a user's handle in the friend array.

Answer №1

Consider updating the declaration of your Post.author reference to the following:

const postSchema = new Schema({
  ...
  author: { 
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Profile',
  },
  ...
})

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

Displaying Child Component in Parent Component After Click Event on Another Child Component: How to Implement Angular Parent/Children Click Events

After delving into Angular 7 for a few weeks, I find myself faced with the challenge of toggling the visibility of a child component called <app-child-2> within a Parent component named <parent>. This toggle action needs to be triggered by a cl ...

Only authenticated users are permitted to write to Firebase databases

Currently, I am in the process of setting up a new Vue JS project for a blog with Firebase integration. The main objective is to allow any logged-in user to create blog posts that are saved in the Firebase real-time database at https://xxx.firebaseio.com/b ...

Transforming the navigation menu using CSS, HTML, and jQuery

One challenge I am facing involves creating a menu similar to the one on http://edition.cnn.com/. I want the clicked button in the menu to receive focus, while the others lose it. Despite trying various methods, I have not been successful. Can someone off ...

When manipulating an array in JavaScript, the final count is wrong and there is an unexpected object

When I click this button, the addToCart function is invoked which dispatches an action to the reducer to add an item to the cart. The goal is to store only one instance of a specific item and increment the amount if the same item is added again. case &apo ...

Using Sweetalert2 to send data via AJAX POST request

Recently, I've been incorporating SweetAlert2 into my project and I want to create an "Add Note" feature. The process involves the user clicking a button, being directed to a page, and then the following script is executed: <script>swal({ ...

Guide on displaying a grid in the center of the screen with a vertical sliding feature

I've noticed certain apps displaying a grid view or form on an alert box with vertical sliding, but I'm clueless about how to make it happen. As far as I know, this can be achieved using jQuery.. Any assistance would be greatly appreciated. Th ...

The specified container does not exist in the DOM: MERN

I am currently working on a project where I aim to develop a Web Application featuring a stock dashboard. During my coding process, I encountered a minor issue that can be seen in this image. My goal is to have a login form displayed on the browser using ...

difficulty in making an https request

My application was developed using OFFICEjs and was functioning properly on LOCALHOST. However, last week it suddenly started throwing an error message - "XHR Error." This issue arose out of nowhere, as I hadn't made any changes to the code over the w ...

Having trouble getting the .replace() Javascript function to work on mobile devices?

I have a code snippet for implementing Google Analytics. Here it is: $(function () { $('.plan-choose-btn a').bind('click', function(e) { //ga load image <% String myaccGAEventUrl = trackGoogleAnalyticsEvent(requ ...

Seeking assistance in optimizing my Javascript code for more efficient canvas rendering

I've created a script for generating random moving lines as a background element for my portfolio. While it runs smoothly on its own, I encounter frame drops when combining it with other CSS animations and effects, especially at the beginning (althoug ...

Developing a Rails application integrated with Pusher or Faye for real

I've been tasked with creating an app similar to this: I'm facing challenges in updating the bids. I am considering using technologies like Pusher or Faye ( or ) and subscribing to each event. However, I'm wondering if there is a more elega ...

Encountering a problem with serializing forms using jQuery

Currently, I am working on form serialization in order to send the file name to the server. However, I have encountered an issue where the serialization values are empty and I am expecting the file name to be included. Within my form, there is an HTML fil ...

Is there a way to locate a specific word within a sentence using JavaScript

I have these lists of answers: For example: const answerList = [{index: 2, answer: nice}, {index: 5, answer: sunday} ...] similar to that Also, I have a sentence: For instance: "hi i'm theo nice to meet you. how are you" My goal is to identify ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

Obtain Information from an Ajax GET Request

My question is fairly straightforward. I have this Ajax function: function fillProductLine(obj) { $.ajax({type: "POST", url: '/orderOnline/index.php/Orders/searchProductLine', async: false, data: { cd_cpl ...

Size of Output from RSA 2048 Encryption Using JSEncrypt

I've been under the impression that the output size of RSA 2048 bit encryption is 256 bytes. However, I keep getting 344 characters as output when using jsencrypt for testing. Can anyone shed some light on why this discrepancy exists? Tool used for o ...

Filtering Sails.js query model based on a collection attribute

Imagine I have these models set up in Sails.js v0.10: Person.js module.exports = { attributes: { name: 'string', books: { collection: 'book', via: 'person' } } }; Book.js module.exports = { ...

Navigating with Express 4

Currently, I am in the process of implementing Passport for user signup by referring to this helpful guide: https://scotch.io/tutorials/easy-node-authentication-setup-and-local Overall, everything is functioning properly except for one issue - after a su ...

The teleport-controls feature is currently not functioning properly in VR mode with Aframe version 0.8.2

Having an issue with the teleport-controls under aframe 0.8.2. When in VR mode using Vive, only the curve appears after touching the trackpad of the controller, but the camera position does not change. However, in flat mode, both the curve and camera posit ...

Pairing strings with arrays

I'm trying to compare elements in two arrays and see if there are any matches. However, I can't seem to get it working correctly. let name; let list = ["Kat", "Jane", "Jack"]; // sample array let input = ["Hey", "i'm", "Jack"]; if (input.fo ...