I’m working on a Facebook clone using Express/MongoDB and I’m working on adding friends. I have it so when a user clicks a button on another users page that says "Send Friend Request" it sends a friend request to them and is stored inside a FriendRequest schema.
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 is notified and they can either accept or deny the request. If they accept the friend request, the status changes from pending to accepted.
Here’s where my code comes in.
I have a friends ejs page and I’m trying to map all accepted friends that a user has in their assigned FriendRequest schema. I’m planning on using this page to show a list of all a users friends. 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 });
});
There is my code. The problem has to do where it says sender: req.user.id. When I have it like that, it only shows a list of friends that I personally have sent friend requests to, and doesn’t show any friends that have sent friend requests to me. And vice versa. If I change sender to receiver it will only show friends that have sent me friend requests.
Here’s an example of an accepted friend when I use console.log. Each one is assigned either sender or receiver.
_id: new ObjectId("6471d4a3a705acadf8af8923"),
sender: {
friends: [],
_id: new ObjectId("6454407483df47caef5004e2"),
username: 'Dagger',
createdAt: 2023-05-04T23:32:04.128Z,
__v: 0
},
When I put both sender: req.user.id and receiver: req.user.id inside the code, nothing shows up at all. I’ve been trying to find a way to make it so if sender OR receiver is equal to req.user.id that it will show the username of the friend but I’m struggling to figure out a way because I can’t use || inside the find method.
I want my code to look like this
const friends = await FriendRequest.find({
sender || receiver: req.user.id,
status: "accepted",
})
but in a way that won’t give me errors.
>Solution :
Your syntax is wrong. You need to use $or operator.
refer operators and projection
const friends = await FriendRequest.find({
$or: [
{sender: req.user.id},
{receiver: req.user.id}
],
status: "accepted"
})
OR
const friends = await FriendRequest.find({
$and: [
{$or: [
{sender: req.user.id},
{receiver: req.user.id}
]},
{status: "accepted"}
]
})