Connect with Friends - Using Express, MongoDB, and EJS for a Seamless Friend Connection

I have been working on creating a social network that allows users to send and interact with friend requests. Currently, I have completed the registration, log-in, and "search for other users" functions.

Once I find and select another user, I am able to display their user information and have added an "Add friend" button.

However, I am struggling to find the right solution for implementing the "Add friend" feature. I have spent some time searching for solutions but have not found the correct one yet. Below, you will find my UserSchema and the 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();
        });
    });
});


Answer №1

If you want to enhance your user schema, consider adding the following:

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

Alternatively, you can use:

connections: userSchema

Choose the option that best fits your needs.

By implementing this, you will create an array within the user document where you can store the IDs of connected friends (who are also users, hence the ref: 'User').

When you need to retrieve users, you can use the following query:

User.find(<ID or criteria to find users>).populate('connections')

Additionally, to add a new friend, simply utilize:

user.connections.push(newFriend._id)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues encountered with JavaScript when trying to use the jQuery API

I'm trying to fetch random quotes using a Mashape API, but when I click the button, nothing happens. I've included the JS and HTML code below. Can anyone spot an issue with the JS code? The quote is not displaying in the div. Thank you! $(' ...

Combining two sets of data in MongoDB

Looking for a way to merge two collections into one while ensuring that duplicates aren't included in the final result. Any suggestions on how to achieve this? I've heard about aggregation and map reduce methods, but I'm not sure which one i ...

Comparing the performance of MongoDB's find and aggregate queries

I'm exploring the performance differences between MongoDB's find and aggregate methods. Is there a way to compare the query performance of aggregate with match and find queries? Currently, I am using JavaScript to measure it. Using find(): var s ...

Exclude previous dates from the front end of ACF date picker

I am using Advanced Custom Fields to post job ads, and I have incorporated a date picker field for the end date of each job ad. <?php if (have_rows('jobs', 'option')): ?> <?php $now = time(); ?> <div i ...

Tips for incorporating Bootstrap classes into a React project, setting the className attribute to an empty string

After setting up Bootstrap and Create-React-App using npm on my local machine, I proceeded to create a new React app. The first component I worked on was counter.jsx: import React, { Component } from 'react'; class Counter extends Component { ...

The React context is currently yielding an undefined value

I am puzzled by this issue. I have double-checked to ensure that the states value is not undefined, and it isn't. However, I am unable to pinpoint where I may be making a mistake. Here is my authContext.js file: const initialState = { isAuthorized: ...

Every time I refresh the page, my table is getting filled with blank rows

I created a simple example featuring a form and some PHP/JavaScript code. The JavaScript is used for form validation, while the PHP is utilized to update a MySQL table. function checkForm(){ var x = document.forms['form1']['first'] ...

What is the process of adding new fields to a model in TypeScript?

I have created a test.model.ts file: export interface ITransaction { description: string; transactionDate: string; isDebit: boolean; amount: number; debitAmount: string; creditAmount: string; } export class Transaction implements ...

Disable the meta tags in Zurb Foundation 5

I have searched extensively online but haven't been able to find a solution for this issue. How can I disable these zurb foundation 5 meta tags in the <head>: <meta class="foundation-mq-small"> <meta class="foundation-mq-small-only"> ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

Angular Bootstrap Popover will now automatically hide after a short period of time due to the removal of the tt_isOpen variable in ui-bootstrap-tpls-0

I recently attempted to implement the ingenious directive created by runTarm for managing angular-bootstrap-popover-hide-after-few-seconds. While using ui-bootstrap 0.11.0.js presented no issues, transitioning to ui-bootstrap-0.12.0 proved problematic as ...

Issue with 1.bundle.js not loading during webpack production build with routing

I have been encountering an issue with my test repository for this specific problem (Link) It appears that the problem lies within the localization file, as I am using react-intl. The development version seems to be functioning properly. This is what&ap ...

display the text content of the chosen option on various div elements

I created a subscription form that includes a category dropdown select field. The selected option's text value needs to appear 4 times within the form. It's all part of a single form. <select name="catid" onchange="copy()" id="catid" class="i ...

Is it possible to find and update specific sections within a field in MongoDB?

There is a field example present in this document: "html": "<!DOCTYPE html PUBLIC \"-\/\/W3C\/\/DTD XHTML 1.0 Strict\/\/EN\" \"http:\/\/www.test.org\/TR\/xhtml1\/DTD\/test.dtd&b ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

I'm having trouble executing the JavaScript function

function contentChange(){ var paragraphs = document.getElementsByTagName("p"); for(var i = 0 ; i < paragraphs.length ; i++){ paragraphs[i].innerHTML = "hello" ;}} contentChange(); I'm struggling to change the content of all ...

What is the best way to emphasize an element on a webpage with Selenium and Python?

Recently, I inherited an existing selenium framework that utilizes Python for scripting. In order to aid in debugging and other tasks, I am interested in implementing a feature that highlights the element currently being acted upon (such as an input box, l ...

What is the best way to sort a combination of numbers and text strings?

Within my table, I have column names enclosed in <th> tags and only numerical values inside <td> tags. When the user clicks on a <th> tag, the sorting algorithm organizes the values in ascending or descending order. .sortElements(function ...

Is there a different option instead of relying on promises for asynchronous requests?

Let's consider a scenario where we have a basic front end application (perhaps using Angular) and a back end app. When the front end app performs a get request, in most cases, the Angular repository will initiate an $http.get request which will return ...

How can I loop through this MongoDB JSON data in a Pug template?

I am trying to display the data from my MongoDB JSON in a specific format shown below: index date 1 1/18/2019, 11:10:05 PM 2 1/18/2019, 11:10:19 PM 3 1/18/2019, 11:13:29 PM This is the MongoDB code snippet: { "_id" ...