错误:默认 Firebase 应用已存在。真的吗?

Ken*_*Ken 7 node.js firebase google-cloud-functions firebase-admin

使用此处的代码:https : //github.com/firebase/functions-samples/blob/master/child-count/functions/index.js部署到 Firebase 时出现“应用程序已存在”错误。我只更改了参考以与我的 Firebase RTD 一起使用。

它很容易修复:

!admin.apps.length ? admin.initializeApp() : admin.app();
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么会发生这种情况?该函数initializeApp()只调用一次。是不是因为应用程序已经在我的其他功能中初始化了?

'use strict';

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

// Keeps track of the length of the 'likes' child list in a separate property.
exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(
    async (change) => {
      const collectionRef = change.after.ref.parent;
      const countRef = collectionRef.parent.child('likes_count');

      let increment;
      if (change.after.exists() && !change.before.exists()) {
        increment = 1;
      } else if (!change.after.exists() && change.before.exists()) {
        increment = -1;
      } else {
        return null;
      }

      // Return the promise from countRef.transaction() so our function
      // waits for this async event to complete before it exits.
      await countRef.transaction((current) => {
        return (current || 0) + increment;
      });
      console.log('Counter updated.');
      return null;
    });

// If the number of likes gets deleted, recount the number of likes
exports.recountlikes = functions.database.ref('/posts/{postid}/likes_count').onDelete(async (snap) => {
  const counterRef = snap.ref;
  const collectionRef = counterRef.parent.child('likes');

  // Return the promise from counterRef.set() so our function
  // waits for this async event to complete before it exits.
  const messagesData = await collectionRef.once('value');
  return await counterRef.set(messagesData.numChildren());
});
Run Code Online (Sandbox Code Playgroud)

该错误还说,“这意味着您多次调用 initializeApp(),而没有提供应用程序名称作为第二个参数。”

我不太确定...

小智 1

我使用:

try
{
   firebaseAdmin.initializeApp()
}
catch(err){
   firebaseAdmin.app()
}
Run Code Online (Sandbox Code Playgroud)