简体   繁体   中英

Cloud Functions: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

Hi I have this function written

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:

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.

The second line imports two functions from the client-side JavaScript SDK, which is made for use in regular applications.

While both SDKs have largely the same API, the two are not binary compatible. 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.

To only use the Admin 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM