我正在做一个Facebook克隆,在过去的几天里,我一直在努力想出发送朋友请求的逻辑。
这是我的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,
},
});
这是我的发送好友请求按钮。输入被隐藏,因此只有按钮显示。
<form action="/friend-requests" method="POST">
<input type="hidden" name="sender" value="<%= id %>" />
<input type="hidden" name="receiver" value="<%= user._id %>" />
<button type="submit">Send Friend Request</button>
</form>
这是我发送好友请求的逻辑。
// POST route to handle the friend request submission
router.post("/friend-requests", (req, res) => {
const { sender, receiver } = req.body;
// Create a new FriendRequest instance
const newRequest = new FriendRequest({
sender,
receiver,
});
// Save the friend request to the database
newRequest
.save()
.then(() => {
// Redirect to a success page or send a response indicating success
res.send("Friend request sent successfully!");
})
.catch((error) => {
// Handle the error appropriately
res.status(500).send("Error sending friend request");
});
});
我想做什么
当用户选择
"Send Friend Request"
在用户配置文件页面上的按钮,一个请求通过并将用户添加到
pending
要求当上述用户检查他们的好友请求时,它会列出所有挂起的请求,他们可以接受也可以拒绝。这是非常基本的东西,但在过去几天里,我梳理了几十个线程后,很难将其全部设置好。
更新-更多代码
这是我的GET
user
个人资料页。它会在您的页面上列出您自己的所有状态更新。
router.get("/:user", function (req, res, next) {
Status.find({}, "content author createdAt")
.sort({ title: 1 })
.exec(function (err, list_status) {
if (err) {
return next(err);
}
res.render("profile", {
status_list: list_status,
id: id,
});
});
});
此代码发布来自
index
页面。
router.post("/:user", [
// Validate and sanitize fields.
body("content", "Content must not be empty.")
.trim()
.isLength({ min: 1 })
.escape(),
// Process request after validation and sanitization.
(req, res, next) => {
const errors = validationResult(req);
const status = new Status({
content: req.body.content,
author: req.body.author,
});
if (!errors.isEmpty()) {
async.parallel((err, results) => {
if (err) {
return next(err);
}
res.render("profile", {
content: content,
author: author,
status,
errors: errors.array(),
});
});
return;
}
status.save((err) => {
if (err) {
return next(err);
}
res.redirect("/");
});
},
]);
我的用户架构
const userSchema = new mongoose.Schema({
firstname: String,
lastname: String,
username: {
type: String,
unique: true,
required: [true, "can't be blank"],
match: [/^[a-zA-Z0-9]+$/, "is invalid"],
index: true,
},
email: {
type: String,
lowercase: true,
unique: true,
required: [true, "can't be blank"],
match: [/\S+@\S+\.\S+/, "is invalid"],
index: true,
},
password: String,
email: String,
createdAt: { type: Date, default: Date.now },
friends: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
],
});