如何在 Node 中初始化 Firebase V9 数据库

How to initialize Firebase V9 database in Node

我想我在 firebase-adminWeb SDK 之间感到困惑 我只是想连接一个计划的作业,它将数据推送到我的 Real-time database

项目结构

Package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "14"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^9.8.0",
    "firebase-functions": "^3.14.1"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

如何正确地将我预定的云函数连接到 Firebase 数据库?

这是我的 index.js 大多数已安排功能的地方

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccountKey.json");
//const { push } = require("firebase/database")

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "myurl"
});

const database = admin.database();

exports.scheduledFunction = functions.pubsub
  .schedule("every 1 minutes")
  .onRun((context) => {
    push(database, "/hello", {
        message: "world"
    })
    return console.log("This will be run every 1 minutes!");
  });

Admin SDK 并不像客户端 SDK 那样完全模块化,因此如果使用 Admin SDK,则必须使用命名空间语法:

const db = admin.database();

exports.scheduledFunction = functions.pubsub
  .schedule("every 1 minutes")
  .onRun((context) => {
    console.log("This will be run every 1 minutes!");
 
    return db.ref('hello').push({ name: "Hellow" });
  });