26. Remove member

In the previous tutorial, we were displaying all members of a group to anyone who is either a member of the group or has received invitation. Now we need to create a function only for the group admin, to remove a member. So in your GroupDetailComponent.vue file, where we are displaying all group members in a modal. Create another table data element that will show a button only to the group admin to remove the member.

<!-- only admin can remove the member -->
<td v-if="user != null && group.createdBy._id == user._id">
    <form v-on:submit.prevent="removeMember">
        <input type="hidden" name="_id" v-bind:value="member._id" required />
        <input type="hidden" name="groupId" v-bind:value="group._id" required />
        <input type="submit" v-bind:value="isDeleting ? 'Deleting...' : 'Remove'" v-bind:isDeleting="disabled" class="btn btn-danger" />
    </form>
</td>

This also requires creating an isDeleting variable in the data() object.

isDeleting: false,

You will see the remove button now, but it is not operational. To make it work, we have to create a method in our methods object that will be called when this form is submitted.

// method to remove member
removeMember: function () {
    const self = this

    // create form data object
    const form = event.target
    const _id = form._id.value
    const formData = new FormData(form)

    // ask for confirmation
    swal.fire({
        title: 'Remove member',
        text: "Are you sure you want to remove this member ?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes'
    }).then(async function (result) {
        if (result.isConfirmed) {
            
            // call an AJAX
            const response = await axios.post(
                self.$apiURL + "/groups/removeMember",
                formData,
                {
                    headers: self.$headers
                }
            )

            if (response.data.status == "success") {
                // remove member from local object
                for (let a = 0; a < self.group.members.length; a++) {
                    if (self.group.members[a]._id == _id) {
                        self.group.members.splice(a, 1)
                        break
                    }
                }
                
                swal.fire("Remove member", response.data.message, "success")
            } else {
                swal.fire("Error", response.data.message, "error")
            }
        }
    })
},

This will ask for confirmation. If the admin confirms, then it will call an AJAX request to remove the member from this group. Along with the request, it will send the group ID so the server will know from which group the member needs to be removed. And also it sends the member ID so the server will know which member needs to be removed.

list group member
remove member

Once it is removed successfully from the server, then it will also remove it from the local array. Now we need to create an API that will handle this request. So open the api/modules/groups.js file and create the following API in it:

// API to remove member by admin
router.post("/removeMember", auth, async function (request, result) {
    // logged-in user
    const user = request.user;

    // member ID
    const _id = request.fields._id;

    // get group ID
    const groupId = request.fields.groupId;

    // check if group exists
    const group = await db.collection("groups").findOne({
        _id: ObjectId(groupId)
    });

    if (group == null) {
        result.json({
            status: "error",
            message: "Group does not exists."
        });
        return;
    }

    // check if you are an admin of the group
    if (group.createdBy._id.toString() != user._id.toString()) {
        result.json({
            status: "error",
            message: "Sorry, you are not group admin."
        });
        return;
    }

    // check if user is a member
    let isMember = false;
    for (let a = 0; a < group.members.length; a++) {
        if (group.members[a]._id.toString() == _id) {
            isMember = true;
            break;
        }
    }

    if (!isMember) {
        result.json({
            status: "error",
            message: "Sorry, the user is not a member of this group."
        });
        return;
    }

    // remove user as member from groups collection
    await db.collection("groups").findOneAndUpdate({
        _id: group._id
    }, {
        $pull: {
            members: {
                _id: ObjectId(_id)
            }
        }
    });

    // send response back to client
    result.json({
        status: "success",
        message: "Member has been removed."
    });
});

You are free to test the app now. Try to delete any member, you will see that it will remove automatically from the list. You do not have to refresh the page.





Please disable your adblocker or whitelist this site!