我打算創建一條路線,讓用戶可以將其他用戶添加爲他/她的朋友,以便他們可以在他們成爲朋友後互相聊天。在node.js和mongoose中添加好友路由的正確方法?
所以基本上,一旦用戶A已經發送到用戶B的請求,用戶B將獲得有關請求現場通知通過socket.io
現在的問題是,我不能拿出自己的解決方案關於如何實現上述場景,從我知道,我應該創建兩條路線GET
和POST
我用貓鼬進行數據庫查詢,插入,更新和刪除
這裏是我的代碼
// GET route for getting the user's information -- Simple route
router.get('/users/:facebook_name', function(req, res) {
User.findOne(facebook_name, function(err, user) {
if (!user) {
res.json({message: "Couldn't find a user by that name"});
return;
}
res.json(user);
});
});
// POST route for adding a friend
router.post('/friendships/create/:facebook_name', ensureAuthenticated, function(req, res) {
// What should i put in this route to make the adding a friend feature works?
User.findOneAndUpdate(facebook_name, function(err, user) {
if (user) {
res.json({message: "You already send a friend request to that person"});
return;
}
// Send a live notification to the other user
socket.emit('sending request', {message: "added you as a friend"});
});
});
用戶模式代碼 - 不是真的知道這一個要麼
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
friends: [{ type: Schema.Types.ObjectId, ref: 'User'}],
facebook: {
id: String,
token: String,
// email: String,
displayName: String,
photo: String
}
});
// Should I even create this schema?
var FriendsRequest = new Schema({
madeBy: [{ type: Schema.Types.ObjectId, ref: 'User'}],
})
module.exports = mongoose.model('User', UserSchema);
module.exports = mongoose.model('FriendsRequest', FriendsRequest);
我不和你們完全誠實的,在POST
路線,我對如何編寫邏輯沒有再用想法,因爲我現在很困惑,用戶B如何獲得實時請求通知?我應該爲此創建另一條路線嗎?
這是我的問題,當涉及到構建稍微複雜的應用程序時,我無法想出如何執行某個功能的好邏輯,即使它看起來很容易。我一直在這個問題上停留了近4個小時,瀏覽和閱讀網絡,但我相信SO是唯一能找到關於如何做某事的線索的地方。
謝謝。
只想知道用戶變量是什麼意思?我如何創建它們? – sinusGob
以及其他用戶如何接受朋友的請求並將其保存到數據庫?當它符合條件時,將把這個問題作爲50賞金。請把更多的細節 – sinusGob
看看問題的更新版本,我添加一些數據庫文件 – sinusGob