Storing user credentials in Firestore after registration - best practices

Hi, I need some assistance with storing user credentials in Firestore after they sign up. Unfortunately, I keep encountering the following error:

Invalid collection reference. Collection references must have an odd number of segments, but userDatabase/QMJiHnhoCchs6MKmPFk7wzTrlau1 has 2.

Below is a snippet of my code. Any help would be greatly appreciated!

const db = getFirestore(app)

//Sign up User Method

createUserWithEmailAndPassword(auth, email, password)
  .then((res) => {
    // Signed in 

   const uid = res.user.uid;

    const data = {
      id: uid,
      email,
      name,
  };



  const ref = collection(db, 'userDatabase', uid)

  console.log(ref);
  setDoc(ref, data)
      .then(() => console.log("Created New User Document Successfully"))
      .catch((e) => console.log("Error", e));

).catch((e) => console.log(e))

By trial and error, I discovered that the issue stemmed from this particular line of code:

const ref = collection(db, 'userDatabase', uid)

I'm unable to pinpoint the exact reason behind it despite trying various solutions. If you can shed some light on this problem, it would be immensely helpful.

createUserWithEmailAndPassword(auth, email, password)
  .then((res) => {
    // Signed in 
    const uid = res.user.uid;

   // const data = {
   //   id: uid,
   //   email,
    //   name,
  //};



  const ref = collection(db, 'userDatabase', uid)

  console.log(ref);
//setDoc(ref, data)
   //   .then(() => console.log("Created New User Document Successfully"))
     // .catch((e) => console.log("Error", e));
    

Answer №1

To bypass this problem, I resolve the issue by substituting the collection with doc

Before proceeding, ensure that you import doc from firebase/firestore as shown below

import { doc } from "firebase/firestore"

Next, replace the following code snippet

const ref = collection(db, 'userDatabase',uid)

With

const ref = doc(db, 'userDatabase',uid)

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

Transferring JavaScript to PHP

I have a challenge where I need to pass a string stored in a variable to a MySQL table using PHP. Currently, my workaround involves using a hidden <input>. I assign the variable value to it and submit it through a form. It works, but it's not e ...

Error in MUI: Unable to access undefined properties (reading 'drawer')

Recently, I encountered an unexpected error in my project using MUI v5.0.2. Everything was working fine just a week ago with no errors, but now I'm facing this issue without any changes made to the code: Error: TypeError: Cannot read properties of un ...

Retrieving outcome of Solidity contract function using web3-1.0.0-beta.27

I am using web3 1.0.0-beta.27 and the pragma solidity is set to ^0.4.2. contract Charity{ function ping() public constant returns (uint) { return 200; } } Currently, I am compiling and calling it in typescript with: import * as fs ...

Is there a way to link a knockout observable to the jquery barrating plugin?

I have integrated the jquery bar-rating plugin with a knockout viewModel. Currently, all ratings need to be manually selected, but I am looking to convert the variable (let's call it rating) into an observable so that the bar automatically updates whe ...

Using codeigniter and JQuery, I have developed a unique Javascript function to selectively extract a specific portion of text

I'm currently working with the following syntax: $("#orderbynumber").autocomplete( { source: "get_orders_by_order_number", messages: { noResults: '', results: function() {} }, select: function( event, ui ) { var select ...

"Unexpected outcome: Angular's HTTP request for a JSON file yields an undefined

Learning Angular has been a challenging experience for me. I am currently working on reading a json file into a chart on my main app page to visualize temperature data from my PI. Despite trying various methods found online, I have not been successful so f ...

Enhancing the appearance of specific text in React/Next.js using custom styling

I have a table and I am currently working on implementing a search functionality that searches for an element and highlights the search terms as they are entered into the search bar. The search function is functional, but I am having trouble with the highl ...

Data is not being refreshed by Ajax

In my forum, users are only allowed to edit and delete their own comments. I have set up an "edit" button that opens a modal when clicked, giving the user access to the data they submitted before. I've written an ajax function to target these fields a ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

Enabling Multiple Login Feature in Node.js

const handleLogin = async (req, res) => { const User = require("../models/user"); const LoginInfo = require('../models/login_info'); try { const { email, mobile, password, otp } = req.body; const params = []; if(ema ...

Display a JSON encoded array using Jquery

Within an ajax call, I have a single json encoded array set: $var = json_encode($_SESSION['pictures']); The json encoded array is stored in a variable called "array" When I try to display the contents of "array" using alert, I get this respons ...

Remove search results in real-time

I'm currently working on implementing a search feature for a web application. While I have made some progress, I am facing an issue with removing items when the user backspaces so that the displayed items match the current search query or if the searc ...

The response from the Ajax call to the WCF is coming back as null

I am currently facing an issue where my ajax call to a function exposed by a WCF service is always returning 'undefined' in the success method, despite the fact that the function on the WCF side is returning the correct answer. I have debugged an ...

Breaking down a large GraphQL request into multiple smaller requests

Having encountered an issue with my request body becoming too large when using the Apollo React Native client, I am exploring options to split this request into smaller chunks. Specifically, I am interested in determining if parallelization is feasible. T ...

Ensuring consistency of Angular route data and maintaining data synchronization

In my Angular application, I have a table that displays a set of items and allows inline editing directly within the table. The data is fetched from an HTTP API through a service, which retrieves the data and injects it into the application. The issue ari ...

Breaking down nested arrays in typescript

After receiving a response from the service, the data included the following: "rows": [ [ "stravi/aa", "202001", "59", "51", "2558.98", "0.5358894453719162", "1.9204668112983725", "140", "2.346630 ...

Unable to retrieve the JSON response item

Currently, I am in the process of setting up an AJAX call with the intention of manipulating the response data. Upon inspecting my browser's network console, this is the response I am seeing: { "message": "success", "file": "dump.xml" } Thi ...

Find the position of an element in an array that includes a specific string value using JavaScript or Node.js

I need help figuring out how to find the index of an array that contains or includes a specific string value. Take a look at my code below to see what I've tried so far: Here is a simple example: var myarr = ["I", "like", "turtles"]; var arraycontai ...

Enhancing a class's properties from its parent component using React

Recently, I decided to dive into React by taking on the challenge of rebuilding the Google Weather app. My main objective is to have the main section update whenever a day is selected. Initially, I believed that updating the props within handleSelectionAt( ...

Filter jQuery search results for classes with identical names

I am new to using jQuery, so please excuse my lack of experience. My current challenge involves 'getting a reference to an object wrapped in a class', but there are multiple classes with the same name. How can I specifically target and retrieve t ...