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.