Hướng dẫn mongodb followers/following

hey I was getting the same problem I figured it out how it can be done. I have two way of writing the code choose as per your choice.

UserSchema

  var UserSchema = new Schema({
    name:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    },
    following: [
    {

        user:{ 
            type: Schema.ObjectId, 
            ref: 'User' 
        },
    }

],
followers: [
    {

        user:{ 
            type: Schema.ObjectId, 
            ref: 'User' 
        },
    }
],
    date:{
        type:Date,
        default: Date.now
    },
});

First Method

User.js

You can use .then and .catch method

    router.post("/user/:user_id/follow-user", (req,res) => {

    // finding user by id (to whom user is going to follow)

    User.findById(req.params.user_id)
        .then(user => {

            //check if follow reqest by user2 is already exist in user1 followers

               if(user.followers.filter(follower => follower.user.toString()=== req.user._id).length > 0 ){
                return res.status(400).json({ alreadyLike : "User already like the post"})
            }

            // the requested user will push and save to followers of other user to whom request has made

            user.followers.push(req.user._id);
            var followedUser = user._id;
            user.save()

            // we will find current user by email you can find it by _id also

            User.findOne({ email: req.user.email })
                .then(user => {

                    // now push the user to following of its own and save the user

                    user.following.push(followedUser);
                    user.save().then(user => res.json(user))
                })
                .catch(err => console.log("error cant follow again you jave already followed the user"))
        })
})

second method

Normal method by call backs

    router.post("/user/:user_id/follow-user",  (req,res) => {

    // finding user by id (to whom user is going to follow)

    User.findById(req.params.user_id, function(err, user) {

        // the requested user will push and save to followers of other user to whom request has made

        user.followers.push(req.user._id);
        var followedUser = user._id;
        user.save(function(err){
            if(err){

                console.log(err)
            }
            else
            {

                // Secondly, find the user account for the logged in user

                User.findOne({ email: req.user.email }, function(err, user) {

                    user.following.push(followedUser);
                    user.save(function(err){
                        if(err){
                            console.log(err)
                        }
                        else{
                            //send success response
                            res.json(user)
                        }
                    });
                });
            }
        });
    });
});

Hướng dẫn mongodb followers/following

Introduction

When deploying a MongoDB cluster on Atlas, the only way to properly secure it is by whitelisting IP addresses allowed to access the cluster. This is quite an effective method but can pose issues in certain scenarios.

I recently deployed a Kubernetes cluster on Google Kubernetes Engine and soon realized there was no definitive IP address range for my pods, inhibitting me from securing the cluster using the Mongo Atlas whitelist. For those who don’t have any background with Kubernetes, the microservice orchestration system maintains a set of apps and services by automatically scaling, recreating, and fixing them. Each instance of an app is called a pod, and because these pods are constantly recreated, cannot have a predefined IP address.

After much searching, I found the only method to get around this (on Google Cloud and most other cloud providers) is by using a NAT (Network Address Translation) gateway. The NAT routes all outgoing traffic within a VPC (Virtual Private Cloud) network through the same IP address, allowing us to whitelist that address. I previously wrote a tutorial on how to setup this infrastructure here, which also includes a brief description of how a NAT gateway works.

Although this solution works great, I realized it was costing me $50/month just to run this NAT gateway. For small projects, this seems ridiculous. Thankfully, Atlas has a tool called Private Network Peering, which allows you to connect your MongoDB Atlas cluster to a Cloud Provider’s VPC network as if they are on the same private network. The issue was, up until a couple months ago, this was only available on AWS. Now, they have added support for Google Cloud and Azure.

Setup Google Cloud

If you already have a Google Cloud account and have created a project, you can skip this step.

Head over to https://cloud.google.com/free for instructions on creating your account. Upon signup, you are given $300 of free credits, so don’t worry about needing to pay for the resources you create in this tutorial.

Create a new project in the Google Cloud console. If you’ve never done this before, see https://cloud.google.com/resource-manager/docs/creating-managing-projects. We will call our project vpc-peering-tutorial.

Setup MongoDB Atlas

Head over to https://www.mongodb.com/cloud/atlas and click Try Free. After signing up you should instantly be brought to a page where you can configure and deploy your first MongoDB Cluster. Do not create a cluster yet, as we need to setup our VPC peer before doing this.

Create VPC Peer

Head over to your Atlas dashboard, create a project if you haven’t already and click Network Access under Security in the sidebar. Click Peering and New Peering Connection. Select Google Cloud Platform and click Next.

Enter in your GCP project ID, which can be found in the Google Cloud Console under Project Info card in the top left. Next, enter your VPC network name, which will be default if you have not changed it or created another. Leave the Atlas CIDR as the default, which should be 192.168.0.0/16. Click Initiate Peering.

Now head over to VPC Network Peering in the GCP Console and click Create connection and Continue. Name the connection atlas-peer, and select default under Your VPC network. Under Peering VPC network select In another project. Now we need to go grab the GCP Project ID and Project Name of our Atlas deployment. Both these values can be found in the Peering tab of the Network Access section in your Atlas dashboard under Atlas GCP Project ID and Atlas VPC Name (if they are not shown yet, wait a few minutes for Atlas to finish initializing the peer).

Hướng dẫn mongodb followers/following

Enter these values into the Project ID and VPC network name forms in GCP and hit Create to finish setting up your VPC Peer.

The last thing we need to do is whitelist our GCP VPC IP address range in Atlas. In the Atlas Network Peering dashboard, you should see a warning above our listed VPC network that ends with “…GCP networks generated in auto-mode use a CIDR range of 10.128.0.0” (you can see this in the screenshot above as well). Copy this CIDR range, click the IP Whitelist tab and click Add IP Address. Enter the copied range under Whitelist Entry and click Confirm. This range will match all regions in our default GCP VPC network (for the current project).

Testing

Before moving on, ensure the VPC peer connection is successfully connected from both GCP and Atlas, and the IP Whitelist we added is finished configuring.

We are going to create a MongoDB cluster. We’ll try and connect to the cluster from our local computer (which should not work) and then create a VM in Google Cloud to ensure it can connect successfully.

Go to your Atlas dashboard and click Clusters under Atlas in the sidebar, then click Build a Cluster. Under Cloud Provider & Region select Google Cloud Platform and iowa (us-central1). Under Cluster Tier, select M10 (any lower will not allow us to use the VPC peer) and under Cluster Name enter test-cluster. Click Create Cluster. The cluster will take a few minutes to spin up.

Local Testing

Ensure you have the Mongo CLI installed, and once the cluster finishes configuring click Connect under the cluster name. Under Create a MongoDB User, enter the username admin and any password (don’t worry about making it too complicated if its only for this tutorial). Click Create MongoDB User then Choose a connection method. Select Connect with the Mongo Shell and click Copy beside the connection string. The string should look something like

mongo "mongodb+srv://test-cluster-2m6rh.gcp.mongodb.net/test" --username admin

Enter it into your terminal or command line and enter your chosen password once prompted. The Mongo shell should try to connect multiple times but fail each time with the following errors:

Unable to reach primary for set test-cluster-shard-0Cannot reach any nodes for set test-cluster-shard-0. Please check network connectivity and the status of the set. This has happened for 2 checks in a row.

After a few tries, it will end with a connection failed exception.

GCP Testing

Now we’ll create a VM on Google Cloud. Head to the GCP Compute Engine VM dashboard and click Create (or Create Instance if you already have a VM).

Under Boot disk click Change, select Ubuntu 18.04 LTS and click Select. Leave all other defaults the same and click Create at the bottom. Once it finishes spinning up, click the arrow beside SSH under Connect and select Open in browser window (you can use your own terminal or command line if you prefer but for simplicity we’ll SSH through the browser). Run the following commands to install the Mongo shell (from here):

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.listsudo apt-get updatesudo apt-get install -y mongodb-org

Now grab that same connection string from before and enter it in. When prompted, enter the same password. You should now see a whole bunch of output, ending with a successful connection to the database:

MongoDB server version: 4.0.10
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
MongoDB Enterprise test-cluster-shard-0:PRIMARY>

Congrats! Now you can connect to your MongoDB Atlas cluster using a private network, removing the need for a NAT gateway when using Kubernetes Engine. To avoid incurring extra charges, ensure to delete the Google Compute Engine VM, the MongoDB Atlas Cluster and the projects created in each.

Hope you enjoyed the tutorial, feel free to leave any comments or questions below!