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;