I am currently developing a social media platform similar to Facebook using Express and MongoDB. One of the features I'm working on is adding friends to user profiles. When a user clicks on a button that says "Send Friend Request" on another user's page, a friend request is sent and stored in a schema called FriendRequest.
const friendRequestSchema = new mongoose.Schema({
sender: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
receiver: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
status: {
type: String,
enum: ["pending", "accepted", "rejected"],
default: "pending",
},
createdAt: {
type: Date,
default: Date.now,
},
});
The user receiving the friend request can either accept or deny it. If they accept, the status changes from pending to accepted.
Now, I need help with my code related to displaying a list of accepted friends for a user on their profile. I have an EJS page called "friends" which should show all accepted friends listed under the FriendRequest schema. For example: /:user/friends.
router.get("/:user/friends", async function (req, res) {
const user = req.user.username;
const friends = await FriendRequest.find({
sender: req.user.id, // my issue
status: "accepted",
})
.populate("sender")
.populate("receiver")
.exec();
res.render("friends", { user, friends });
});
The problem lies with the line where it specifies sender: req.user.id. This only displays friends whom the current user has sent requests to, but not those who have sent requests to them. Switching sender to receiver would only show friends who have sent requests to the user. How can I modify the code so that it fetches friends based on both sender and receiver being equal to req.user.id?
When I try to include both sender: req.user.id and receiver: req.user.id, no results are displayed. I am struggling to find a way to retrieve friends where either sender or receiver matches req.user.id without using || inside the find method.
This is how I want it to look:
const friends = await FriendRequest.find({
sender || receiver: req.user.id,
status: "accepted",
})
I wish to achieve this without encountering any errors in my code.