Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this?

Current Code

setDoc(
  query(collectionRef),
  //     db.collection('users').doc(user.uid).set(

  {
    email: user.email,
    lastSeen: serverTimestamp(),
    photoURL: user.photoURL
  }, {
    merge: true
  }
);

Past Code that referenced document UID:

Answer №1

To properly use the setDoc() function, make sure that the first parameter is a valid DocumentReference:

import { doc, setDoc } from "firebase/firestore"

const document = doc(db, "users", user.uid);

setDoc(document, {
  email: user.email,
  lastSeen: serverTimestamp(),
  photoURL: user.photoURL
}, {
  merge: true
}).then(() => console.log("Document updated successfully"));

Answer №2

If you prefer, you can also utilize the updateDoc() method.

import {
  doc,
  updateDoc
} from "firebase/firestore"

update(doc(db, "users", user.uid, {
  email: user.email,
  lastSeen: serverTimestamp(),
  photoURL: user.photoURL
}).then(() => console.log("Data successfully updated"));

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

What could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

I am unable to achieve negative X degree rotation of the image while using mousemove to rotate it

I need assistance with moving a picture in 3D. I want the offsetX of the mouse to be positive when it's past half of the picture, and negative otherwise. How can I achieve this effect for rotation degrees? This is what I have tried: $('#img ...

What is the best way to pass a JSON object from R to Plumber in a format that JavaScript can interpret as an array instead of

My goal is to receive a JSON raw response from R Plumber and then utilize it in Angular. However, I am encountering an issue where the JavaScript Framework is interpreting it as a string instead of recognizing it as JSON format. "[{\"id&bsol ...

What is the best location to initialize a fresh instance of the Firebase database?

Is the placement of const db = firebase.database() crucial in a cloud function script? For instance, in a file like index.ts where all my cloud functions are located, should I declare it at the top or within each individual function? const db = firebase. ...

The delete_node() function in jstree does not seem to be removing nodes

In my attempt to create a custom context menu for different nodes, I've managed to display different labels for clicks on folders or files. However, I am facing some challenges when trying to delete them. Take a look at my code snippet. Due to diffic ...

Creating an interactive table with the power of FPDF and PHP

I have developed a unique Invoice System that allows users to customize the number of headings and fields using FPDF in conjunction with PHP. Subsequently, I can input the heading names and field values into HTML input fields. However, I am encountering a ...

Encountering a 400 bad request error while trying to post data using

const fetch = require("node-fetch").default; let iApi = express.Router(); iApi.post("/update/:name/:value", async (req, res) => { const name = req.params["name"]; ...

Retrieve the heading from a pop-up box

This jQuery tooltip allows for popups from another HTML page to be created. UPDATE: I have provided an example HERE The issue arises when trying to retrieve the title from the popup. Currently, using document.title displays the title of the current page ...

Using the React key attribute for components without distinct identifiers

When dealing with a situation where users need to provide a list of timeframes, it can be tricky to generate a unique key for each component in React. Simply using the index of the array is not sufficient, as items can be removed from the middle of the lis ...

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

Error message encountered in AngularJS when trying to send Fullcalendar: TypeError - Cannot access property '__id' of an undefined object

Recently, I integrated angular-ui-calendar into my website. Within the controller, I implemented the following: define(['underscore'], function (_) { "use strict"; var SearchController = function ($scope, $location, OrdersService, U ...

Is there a universal method to disregard opacity when utilizing jQuery's clone() function across different web browsers?

I've encountered a situation where I need to allow users to submit a new item to a list within a table, and have it smoothly appear at the top of the list. While using DIVs would make this task easier, I am working with tables for now. To achieve thi ...

Set boundaries for the width and height of an image in the input field

Looking to restrict the size of an image in an input field using HTML, CSS, and JavaScript/jQuery. Goal is to maintain a perfect square aspect ratio for profile photo uploads (for example, 200x200 or 300x300). ...

Tips for displaying an HTML page using JavaScript

In my project, I am working with an .html file (File X) that needs to immediately open another .html file (File Y) based on a certain value. Could someone provide guidance on the best way to achieve this using JavaScript? Additionally, I would like the pa ...

The operation of moveImage does not exist

Currently, I am attempting to incorporate setInterval with my moveImage function in order to modify the position of an image. Here is a snippet of my code: <template> <div class="randImg"> <img v-bind:style="{top: imgTop + 'px&ap ...

The Navigation Stops Working Following an Automated Redirect from a 404 Page to the Homepage with next/router and useEffect()

I encountered a problem with next/router. I created a '404 Page' and configured it to redirect clients back to the home page router.push('/') after 3 seconds. However, when clients return to the main page, they encounter a console error ...

How to clear input fields in Ant Design ReactJS components

Utilizing the form list component from antd in my react.js project https://ant.design/components/form/#Form.List I have a basic form list set up where I can easily add or remove fields. At times, I need to reset the form and remove any additional items t ...

Working with Firebase and handling asynchronous data retrieval: Implement success and error callbacks with the

I'm currently working on an Angular application that includes the following function: $scope.retrieveProjectData = function() { $scope.projectNumberNoChange = false; // Only fetch data if the ProjectNumber has changed if (cur ...

What could be causing my NextJS application to not recognize the _document.tsx file?

Seeking assistance in understanding why my _document.tsx is not loading properly within my nextJS application. My Attempts So Far I have been diligently following the NextJS documentation for creating a custom _document.js. Despite my efforts, I am unable ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...