无法使用 Firebase 实时数据库读取/写入数据。

huangapple go评论71阅读模式
英文:

Can't read/write data with Firebase Realtime Database

问题

以下是您要翻译的内容:

根据Firebase数据库设置,我无法读取/写入任何内容。我已经搜索了几个小时,尝试了不同的方法,但什么都没有用。我正在使用Discord.js,所以我将删除与Firebase无关的内容。目前,我只是为了测试目的而硬编码了值。

require("dotenv").config();

const { initializeApp } = require('firebase/app');
const { getDatabase, ref, set } = require('firebase/database');

const firebaseConfig = {
  apiKey: process.env.API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID,
  measurementId: process.env.MEASUREMENT_ID,
};

// 初始化Firebase
const app = initializeApp(firebaseConfig);

// 初始化实时数据库
const database = getDatabase(app);

function writeUserData(userId, name, email, imageUrl) {
  const db = getDatabase();
  set(ref(db, 'users/' + userId), {
    username: name,
    email: email,
    profile_picture: imageUrl
  });
}

client.on("ready", () => { // 当机器人上线时
  console.log("准备就绪!");
  writeUserData("UserId", "Terry", "email@gmail.com", "https://imgur.com/t/bees/3bt83")
});

我的firebaseConfig信息都是正确的。我的读/写权限都为true。

任何帮助都将不胜感激。

我已经尝试了官方的Firebase文档以及其他关于同样问题的论坛。

英文:

Following the Firebase Database Setup, I can't Read/Write anything. I've been googling for hours trying different approaches and nothing is working. I'm using Discord.js so I'll remove the stuff unrelated to Firebase. For now I'm just hard coding the values for testing purposes.

require("dotenv").config();

const { initializeApp } = require('firebase/app');
const { getDatabase, ref, set } = require('firebase/database');

const firebaseConfig = {
  apiKey: process.env.API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID,
  measurementId: process.env.MEASUREMENT_ID,
};

// Initialize firebase
const app = initializeApp(firebaseConfig);

// Initialize Realtime Database
const database = getDatabase(app);

function writeUserData(userId, name, email, imageUrl) {
  const db = getDatabase();
  set(ref(db, 'users/' + userId), {
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

client.on("ready", () => { // when bot goes online
  console.log("Ready!");
  writeUserData("UserId", "Terry", "email@gmail.com", "https://imgur.com/t/bees/3bt83")
});

All of my firebaseConfig info is correct. My Read/Write permissions are both true.

Any help is appreciated.

I've tried the official Firebase documentation as well as other forums regarding the same problem.

答案1

得分: 1

从您提供的代码中,可能有几个问题导致了问题。让我们一步一步地检查它们:

Firebase初始化:您正确初始化了Firebase应用程序,但是在调用getDatabase()时,您没有将应用程序实例作为参数传递。将const db = getDatabase(); 修改为 const db = getDatabase(app); 以使用初始化的应用程序。

设置用户数据:在您的writeUserData函数中,您试图使用ref(db, 'users/' + userId)设置用户数据。然而,您已经在全局范围内使用const database = getDatabase(app); 获得了ref。所以,您可以直接使用ref(database, 'users/' + userId) 而不是创建一个新的db变量。

更新代码如下:

set(ref(database, 'users/' + userId), {
  username: name,
  email: email,
  profile_picture: imageUrl
});

看起来您没有定义在 client.on("ready", () => { ... }); 块中使用的client对象。确保您已经进行了必要的Discord.js设置,并且client对象被正确定义。

在做出这些更改之后,代码应该如下所示:

require("dotenv").config();
const { initializeApp } = require('firebase/app');
const { getDatabase, ref, set } = require('firebase/database');
const { Client } = require('discord.js');

const firebaseConfig = {
  apiKey: process.env.API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID,
  measurementId: process.env.MEASUREMENT_ID,
};

// 初始化Firebase
const app = initializeApp(firebaseConfig);

// 初始化实时数据库
const database = getDatabase(app);

function writeUserData(userId, name, email, imageUrl) {
  set(ref(database, 'users/' + userId), {
    username: name,
    email: email,
    profile_picture: imageUrl
  });
}

const client = new Client();

client.on("ready", () => {
  console.log("准备就绪!");
  writeUserData("UserId", "Terry", "email@gmail.com", "https://imgur.com/t/bees/3bt83");
});

client.login("YOUR_DISCORD_TOKEN"); // 用您的实际Discord机器人令牌替换

确保您用实际的Discord机器人令牌替换"YOUR_DISCORD_TOKEN"。如果仍然遇到问题,请确保您的Firebase实时数据库规则已正确设置,同时检查您的环境变量以确保它们设置正确。

英文:

From the code you provided, there are a few issues that could be causing the problem. Let's go through them step by step:

Firebase Initialization: You are initializing the Firebase app correctly, but when you call getDatabase(), you're not passing the app instance as an argument. Modify the line const db = getDatabase(); to const db = getDatabase(app); to use the initialized app.

Setting the User Data: In your writeUserData function, you're trying to set the user data using ref(db, 'users/' + userId). However, you've already obtained the ref in the global scope using const database = getDatabase(app);. So you can directly use ref(database, 'users/' + userId) instead of creating a new db variable.

Update the line as follows:

set(ref(database, 'users/' + userId), {
  username: name,
  email: email,
  profile_picture: imageUrl
});

It seems like you haven't defined the client object used in the client.on("ready", () => { ... }); block. Make sure you have the necessary Discord.js setup and the client object is defined correctly.
After making these changes, the code should look like this:

require("dotenv").config();

const { initializeApp } = require('firebase/app');
const { getDatabase, ref, set } = require('firebase/database');
const { Client } = require('discord.js');

const firebaseConfig = {
  apiKey: process.env.API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID,
  measurementId: process.env.MEASUREMENT_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Realtime Database
const database = getDatabase(app);

function writeUserData(userId, name, email, imageUrl) {
  set(ref(database, 'users/' + userId), {
    username: name,
    email: email,
    profile_picture: imageUrl
  });
}

const client = new Client();

client.on("ready", () => {
  console.log("Ready!");
  writeUserData("UserId", "Terry", "email@gmail.com", "https://imgur.com/t/bees/3bt83");
});

client.login("YOUR_DISCORD_TOKEN"); // Replace with your Discord bot token
Make sure you replace "YOUR_DISCORD_TOKEN" with your actual Discord bot token. If you're still having issues, make sure your Firebase Realtime Database rules are properly set to allow read and write access. Double-check your environment variables as well to ensure they are correctly set.

答案2

得分: 0

"Turns out I needed to use Admin access, it's weird I couldn't find any mention of people trying this anywhere online. For those who may be seeing this in the future and have the same problem, try using the admin sdk."
转换为中文:原来我需要使用管理员访问权限,很奇怪我在网上找不到任何人尝试过这个的提及。对于将来可能遇到相同问题的人,请尝试使用管理员SDK。

英文:

Turns out I needed to use Admin access, it's weird I couldn't find any mention of people trying this anywhere online. For those who may be seeing this in the future and have the same problem, try using the admin sdk.

答案3

得分: 0

这是一个奇怪的解决方案,但对我来说确实有效,将所有对 getDatabase(app) 的使用都更改为只调用 getDatabase(),并且在需要使用 db 时始终调用该函数。将

getDatabase(app);

更改为

getDatabase();
英文:

This is a weird solution, but it is what worked for me though,
change all use of getDatabase(app) to just getDatabase() and also always calling the function when db is needed. Change

getDatabase(app);

to

getDatabase();

huangapple
  • 本文由 发表于 2023年5月21日 14:52:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定