简体   繁体   English

交友系统 - Express, MongoDB, EJS

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

I want to create a social.network thus allowing users to send and interact with frind requests.我想创建一个 social.network,从而允许用户发送 frind 请求并与之交互。 As of now I have created the register, log-in and "search for other users function".到目前为止,我已经创建了注册、登录和“搜索其他用户功能”。

When I find and select another user, I display their user-info and have created a "Add friend" button.当我找到另一个用户 select 时,我会显示他们的用户信息并创建一个“添加朋友”按钮。

Can anyone help me in a direction of the creation of the "Add friend" option?任何人都可以帮助我创建“添加朋友”选项吗? I have looked around for some time now, and not been able to find the correct solution.我已经环顾四周一段时间了,但找不到正确的解决方案。 Below I have attached my UserSchema and route for finding users:下面我附上了我的 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();
        });
    });
});


You can add something like this in your user schema:您可以在用户架构中添加类似这样的内容:

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

OR要么

friends: userSchema

Take the one which suits you.拿适合你的那个。

What that will do is add an array to the user, Then you can store IDs of friends.(Who are other users, hence the ref: 'User' )这样做的目的是向用户添加一个数组,然后您可以存储朋友的 ID。(其他用户是谁,因此ref: 'User'

Then, When you have to fetch users you can do:然后,当您必须获取用户时,您可以执行以下操作:

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

Also, To push a new friend simply use: user.friends.push(newFriend._id)此外,要推送新朋友,只需使用: user.friends.push(newFriend._id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM