Updating user data with Firebase cloud functions

For my e-commerce project, I am looking to utilize the Google Maps API to input the location of a user's shop.

I have successfully utilized Google Cloud Functions to insert the latitude, longitude, and address data.

Currently, the data can be inserted into a collection named locations. However, my goal is to link this information to the user profile collection.

How can I add latitude, longitude, and user address details to the user profile collection?

Here is the code included in my index.js file:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const Firestore = admin.firestore;
const db = Firestore();

const axios = require("axios");
const cors = require("cors")({
    origin: true
});

const googleMapsApiKey = "AIzaSyAnp23T2tbYj9Ho8uYmcE6W4KnbvZKlEjc";

exports.geocodeAddressAndSave = functions.https.onRequest(async (request, response) => {
    try {
        let address = encodeURI(request.body.address);
        let { data } = await axios.get(
            `https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${googleMapsApiKey}`
        );

        if (data.status !== "OK") {
            //no results
            return cors(request, response, () => {
                response.status(200).send("No Results");
            });
        }

        const geocodedLocation = data.results[0];
        const objGeolocation = {
            address: geocodedLocation.formatted_address,
            geoPoint: new admin.firestore.GeoPoint(geocodedLocation.geometry.location.lat, geocodedLocation.geometry.location.lng)
        }

        //firebase

        await 

        db.collection('locations').add(objGeolocation);

        return cors(request, response, () => {
            response.status(200).send(objGeolocation);
        });
    } catch (error) {
        return cors(request, response, () => {
            console.log(error);
            response.status(500).send();
        });
    }
});

In my Vue.js code:

<template>
  <!-- Vue template content -->
</template>

<script>
// Relevant JavaScript code here
</script>

I aim to store this data within the Profile collection. https://i.sstatic.net/BgvGI.png https://i.sstatic.net/MdGyp.png

Answer №1

In order to update a user's profile, you must first obtain their UID and then proceed with the update process. It is crucial to ensure that this operation is secure, so make sure to securely pass the UID when performing the update. For more information on handling user info in Cloud Functions in Firebase, refer to: Getting user info from request to Cloud Function in Firebase

Once you have obtained the UID, you can update the user's profile document using the following code snippet:

db.collection('profiles').doc(uid).update({ ... });

Answer №2

I made updates to my Vue code.

let user = firebase.auth().currentUser;

      db.collection('Profile').doc(user.uid).update({ 
            address: newData.address,
            latitude: newData.geoPoint._latitude,
            longitude: newData.geoPoint._longitude,
        });

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

How can I populate an array to use in a datatable when rendering?

How can I ensure that my datatable renders with the proper data on my webpage without needing to interact with the sort button? Where should I populate the array for use in a datatable so that it occurs before the rendering? export function MyComponent() ...

Encountering an error: Module missing after implementing state syntax

My browser console is showing the error message: Uncaught Error: Cannot find module "./components/search_bar" As I dive into learning ReactJS and attempt to create a basic component, this error pops up. It appears after using the state syntax within my ...

Tips for displaying the response next to the corresponding table data (td) cell

When I click the fourth button, the response is showing on the first td. I want to show the response next to the respective td. Below is my code, can someone help me? Thanks. (i.e., here I am getting the $status using a query, but I want this status to di ...

Vue.js Dynamic Class Binding Fails to Update

As I delve into learning Vue Js, I have been working on a simple todo app. One interesting thing I've done is binding a class to my todo items based on whether todo.completed is true or not: <a v-bind:class="{iscomplete : todo.completed}& ...

Combining data from various JSON files to create dynamic charts with Highcharts

At this moment, my Highchart code is set up in a way where I want to replace the static data-series values within the HTML file with information loaded from a JSON file. The current code appears as follows: <!doctype html> <script type="text/jav ...

Encountering a white screen and MIME Type Error when attempting to deploy a Vite app on GitLab Pages

I am facing an issue while trying to deploy my Vite application on Gitlab Pages. The page only displays a blank screen and the following errors are shown: The CSS and JS files from the static directory cannot be loaded due to MIME type mismatch (X-Content ...

Switch up the link color when it pops up

Is there a method to change the link color to gray without encountering glitches like on my site, where it mistakenly shows "Quick Nav."? Click here to view the page with the glitch I only want this particular link to be bold and not any other links. He ...

Encountering difficulties in generating a binary from a nodejs application with pkg

I am having trouble generating a binary executable from my nodejs app using the pkg command. My nodejs app is simple and consists of only three .js files: index.js, xlsx_to_pdf.js, and xlsx_extractor.js. This is how my package.json file looks like: { & ...

Invoking functions with JavaScript objects

Can anyone help me figure out what is wrong with the following JavaScript code? <form> What is 5 + 5?: <input type ="number" id ="num_answer;"/> </form> <script> function basic_math(){ var num_val = document.getElem ...

Struggling to get my JavaScript function for calculating one rep max to work, need some help figuring out the issue

I have been working on a one rep max calculator using the Epley Formula. However, when I try to call the function, it returns as undefined. I have utilized the parameters weight and reps, both of which are parsed as integers, believing that they would be e ...

Firebase (vue.js) is not recognizing the .orderByChild() function

I have been attempting to organize my data using .orderByChild, but it seems that the data is being filtered by the node's name. Here is the code I added on Firebase : "concerts": { ".indexOn": "expires" } Below is the snippet of code from my ind ...

Tips on appending a parameter to an image URL using JavaScript

On my website, I am able to insert images with specified width and height using this code: <img src="image.php?w=100&h=100"> I would like the image size to change based on the device screen width. For screens smaller than 600px, I want to displa ...

I keep encountering the issue where nothing seems to be accessible

I encountered an error while working on a project using React and Typescript. The error message reads: "export 'useTableProps' (reexported as 'useTableProps') was not found in './useTable' (possible exports: useTable)". It ...

jQuery functions not functioning properly when triggered by an event

I encountered an issue with my page using jQuery and Bootstrap. Everything was functioning properly until I tried calling a function on an event, which resulted in the console showing an error message saying $(...).function is not a function. For example: ...

What can I do to prevent masonry images from piling on top of one another?

I have been working on creating a photo gallery using the Bootstrap 5 example on masonry, and everything is working well so far. I have also successfully implemented modal boxes. However, the only issue I'm facing is with the JS Image Loaded not preve ...

Insert the video link and preview it with live option

Currently working on a form that allows users to input a video URL. The form will be a standard input field where they can enter a URL such as: http://video.google.com/videoplay?docid=1299927595688205543 I want to include a button within the form labeled ...

Can a single component support multiple v-model bindings simultaneously?

Having a component used in two different places with an <input v-model="model" >, I face the challenge of watching this v-model in my component. The issue arises as the model changes - one place has model = array.val1 while the other has model = arra ...

Unable to change the value of selected items in checkbox event within a React context

Today marks the beginning of my journey into developing a React application. I am currently faced with the challenge of retrieving the row ID of a checked checkbox in a React table. Utilizing hooks, I have managed to transfer the states to another compone ...

What makes Twitter Bootstrap special that modal events function in JQuery but not in pure JavaScript?

When working with the Twitter Bootstrap modal dialog, there is a set of events that can be utilized with callbacks. For instance, in jQuery: $(modalID).on('hidden.bs.modal', function (e) { console.log("hidden.bs.modal"); }); I ...

Using AJAX to dynamically edit and update PHP data

The information displayed on my index.php page is fetched from a database using the mysqli_fetch_array function. The data is presented in a table format with fields like Name, Age, Email, and Update. An edit button allows users to modify the data. Here is ...