我正在尝试通过客户端(Android)的Firebase Function调用在Firebase Firestore中创建一个文档。
正如文档所说,我们可以在未来的文档上创建一个参考,并在几行之后设置信息:Firebase GitHub
我在客户端上获得了文档 ID,但文档未添加到 Firestore,因此"set()"不起作用。
可能出了什么问题?
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
export const createPack = functions.https.onCall((data) => {
admin.initializeApp(functions.config().firebase);
console.log("[CREATE PACK] START");
const db = admin.firestore();
var document = db.collection("packs").doc();
console.log("[CREATE PACK] GOT REF");
document.set({
title: data.title,
date: data.date,
total: data.total,
activated: 0
});
let packId = document.id;
console.log('[CREATE PACK] PACK ID ' + packId);
console.log('[CREATE PACK] END');
return {
"id": packId
};
});
我希望将数据添加到Firestore。
以下方法应该有效:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
export const createPack = functions.https.onCall((data) => {
console.log("[CREATE PACK] START");
const db = admin.firestore();
var documentRef = db.collection("packs").doc();
console.log("[CREATE PACK] GOT REF");
return documentRef.set({
title: data.title,
date: data.date,
total: data.total,
activated: 0
})
.then(() => {
const packId = documentRef .id;
console.log('[CREATE PACK] PACK ID ' + packId);
console.log('[CREATE PACK] END');
return { "id": packId };
});
});
您必须在异步操作后返回一个承诺,请参阅文档:https://firebase.google.com/docs/functions/callable。(我还建议您观看Firebase视频系列中的3个视频,标题为"学习JavaScript承诺":https://firebase.google.com/docs/functions/video-series/)
另外,请注意,自 Cloud Functions 版本 1.0 起,"初始化时无法再传入functions.config().firebase
"。请参阅 https://firebase.google.com/docs/functions/beta-v1-diff#new_initialization_syntax_for_firebase-admin。最后请注意,您必须在云函数本身之外进行初始化。