简体   繁体   中英

Friend Request System - Express, MongoDB, EJS

I want to create a social.network thus allowing users to send and interact with frind requests. 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.

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:

//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' )

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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