Wednesday, 19 April 2017

Friend Request System with Express & MongoDB

I am trying to let users send friend requests to other users similar to that of Facebook and other social media platforms. I have started creating this functionality, but quickly got stuck since I am new to mongoDB and the whole Schema thing.

Here are the models I currently have:

// User Schema
var UserSchema = new Schema({
    _id: {
        type: Number
    },
    name: {
        type: String
    },
    username: {
        type: String,
        index: true
    },
    password: {
        type: String,
        required: true
    },
    email: {
        type: String
    },  
    friends: [{
        friendName: {
            type: Schema.ObjectId,
            required: true,
            ref: 'User'
        },
        duration: {
            type: Number
        }
    }]
});


// Friendship Schema
var FriendshipSchema = new Schema({
    participants: [{
        type: Schema.Types.ObjectId, 
        ref: 'User'
    }],
    requestTo: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    accepted: {
        type: Boolean, 
        default: false
    },
    user: {
        type: Schema.ObjectId, 
        ref: 'User'
    }
});

var Friendship = module.exports = mongoose.model('Friendship', FriendshipSchema);

var User = module.exports = mongoose.model('User', UserSchema);

This is as far as I have gotten. From here, I do not know how to use these schemas to establish friendships between 2 users. My ultimate goal is to have a button on a webpage that sends a friend request to the intended recipient, where they can then accept or deny the request.

Any help with this would be awesome, since I do not know what to do from here with these 2 schemas. Thanks!



via jblew

No comments:

Post a Comment