[英]Cloud Functions: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
Hi I have this function written嗨,我写了这个 function
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { setDoc, doc } = require("firebase/firestore");
admin.initializeApp();
const db = admin.firestore();
// // Create and Deploy Your First Cloud Functi
exports.idiot = functions.pubsub.schedule('* * * * *').onRun(async (context) => {
// // Add a new document with a generated id
const moment = require('moment')
console.log("testtesttest 603")
console.log(db.collection)
const Questions =
{
Questions: {
QoD: "test",
Upvotes: 0,
}
}
const Comments =
{
Comments: {
Body: "hello",
Replies: [],
Upvotes: 0
}
}
await setDoc(doc(db, "Questions", moment().format('MMM Do YYYY')), Questions);
await setDoc(doc(db, "Comments", moment().format('MMM Do YYYY')), Comments);
});
And suddenly I am getting this error:突然我收到这个错误:
2022-09-28T00:59:00.846793Z ? idiot: FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
2022-09-28T00:59:00.848764071Z D idiot: Function execution took 9 ms. Finished with status: error
But it was writing to the document before.但是它之前是在写文档。
Is there any reason why this error would pop up when the script was working before?之前脚本运行时是否会弹出此错误?
You're importing two different SDKs here:您在此处导入两个不同的 SDK:
const admin = require("firebase-admin");
const { setDoc, doc } = require("firebase/firestore");
That first line imports the Firebase Admin SDK, which is designed to be used in trusted environments such as Cloud Functions.第一行导入 Firebase Admin SDK,它设计用于 Cloud Functions 等可信环境。
The second line imports two functions from the client-side JavaScript SDK, which is made for use in regular applications.第二行从客户端导入两个函数 JavaScript SDK ,用于常规应用。
While both SDKs have largely the same API, the two are not binary compatible.虽然两个 SDK 的 API 大体相同,但两者并不二进制兼容。 So the
db
variable points to a Firestore
object the Admin SDK, while your doc
function is expecting a Firestore
object from the client-side JavaScript SDK.因此,
db
变量指向Firestore
object 和 Admin SDK,而您的doc
function 期望来自客户端 JavaScript SDK 的Firestore
object。
To only use the Admin SDK:仅使用管理员 SDK:
const questionRef = db.doc("Questions", moment().format('MMM Do YYYY'));
await questionRef.set(Questions);
And then the equivalent for the comments.然后相当于评论。
In the documentation, you'll want to look for the v8
code samples for this syntax, like here in the documentation on writing to a document reference .在文档中,您需要查找此语法的
v8
代码示例,例如文档中有关写入文档参考的此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.