我目前有一個用戶系統,用戶可以將其他朋友添加爲朋友。這是我的路線:MongoDB + NodeJS + Express - 用戶可以將朋友請求發送給已經是他們的朋友的人
app.post("/addFriend", function(req, res) {
var conditions = {
$or: [
{$and: [
{username: req.body.globalUserName},
{$or: [
{'pendingFriends._id': {$ne: req.user._id}},
{'friends._id': {$ne: req.user._id}}
]}
]},
{$and: [
{username: req.user.username},
{$or: [
{'pendingFriends._id': {$ne: req.body.globalUserId}},
{'friends._id': {$ne: req.body.globalUserId}}
]}
]}
]
}
var update = {
$addToSet: {pendingFriends: { _id: req.user._id, username: req.user.username, language: req.user.language, profilePicture: req.user.profilePicture}}
}
User.findOneAndUpdate(conditions, update, function(error, doc) {
if(error) {
console.log(currentTime + " - FRIEND_REQUEST_SEND_ERROR: '" + req.user.username + "' TRIED TO SEND A FRIEND REQUEST TO '" + req.body.globalUserName + "'");
}
else {
console.log(currentTime + " - FRIEND_REQUEST_SENT: '" + req.user.username + "' SENT A FRIEND REQUEST TO '" + req.body.globalUserName + "'");
}
res.redirect("/talk");
});
});
所以這就是它的工作原理。
U1向U2發送好友請求。
U1被添加到U2的pendingFriends中。
如果U2接受,U1轉到U2的朋友,U2轉到U1的朋友。
但是,我現在有兩個錯誤,我知道。如果U1向U2發送好友請求,而U1在U2的pendingFriends中,則U2可以向U1發送好友請求。另外,如果U1向U2發送好友請求,U2接受後,U1和U2仍然可以向對方發送好友請求。
我該如何解決這個問題?順便說一下,req.user是執行操作的用戶(發送表單等)。 req.body.globalUserId是執行操作的用戶試圖添加的用戶的ID。
EDIT(用戶通過用戶請求模式):
UserSchema = new mongoose.Schema({
username: String,
email: String,
password: String,
language: { type: String, default: "English" },
profilePicture: { type: String, default: "/images/talk/blank-profile-picture.png" },
status: String,
pendingFriends: [this],
friends: [this]
})
我認爲這是因爲或操作。 – Remario