簡體   English   中英

交友系統 - Express, MongoDB, EJS

[英]Friend Request System - Express, MongoDB, EJS

我想創建一個 social.network,從而允許用戶發送 frind 請求並與之交互。 到目前為止,我已經創建了注冊、登錄和“搜索其他用戶功能”。

當我找到另一個用戶 select 時,我會顯示他們的用戶信息並創建一個“添加朋友”按鈕。

任何人都可以幫助我創建“添加朋友”選項嗎? 我已經環顧四周一段時間了,但找不到正確的解決方案。 下面我附上了我的 UserSchema 和查找用戶的路線:

//User Schema
const UserSchema = new mongoose.Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
},{ collection: 'Users' });




//Get single user based on ID
router.get('/user/get:id', ensureAuthenticated, function (req, res) {
    MongoClient.connect(DBUri,{useUnifiedTopology: true }, function (err, db) {
        let dbo = db.db(DBName);
        const query = {_id: objectId(req.params.id)}
        dbo.collection("Users").find(query).toArray(function(err, resultTasks) {
            if (err) throw err;
            res.render('../View/findFriend', {
                resultTasks: resultTasks
            });
            db.close();
        });
    });
});


您可以在用戶架構中添加類似這樣的內容:

friends: [{ type: ObjectId, ref: 'User' }],

要么

friends: userSchema

拿適合你的那個。

這樣做的目的是向用戶添加一個數組,然后您可以存儲朋友的 ID。(其他用戶是誰,因此ref: 'User'

然后,當您必須獲取用戶時,您可以執行以下操作:

User.find(<ID or whatever you have to find Users>).populate('friends')

此外,要推送新朋友,只需使用: user.friends.push(newFriend._id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM