TikTak
TikTak

Reputation: 803

I can not write data from the Firebase Cloud Functions in Firebase Firestore

How several days ago I started using Firebase Cloud Functions and I can not write data to the database. Could you help me. Thanks in advance.

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

admin.initializeApp(functions.config().firebase);

exports.userCreated = functions.auth.user().onCreate(event => {
    let userId = event.data.uid;
    let userName = event.data.displayName;

    admin.firestore()
    .collection("users")
    .doc(userId)
    .set({
        name: userName,
        city: "",
        rating: 0
    });
});

Upvotes: 1

Views: 1536

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

Please see the documentation to understand how Cloud Functions works with async code.

You're not returning a promise from your function. If your function performs any async work that yields a promise, you have to indicate to Cloud Functions wait for that work to complete by returning a promise that resolves when the work is complete:

exports.userCreated = functions.auth.user().onCreate(event => {
    let userId = event.data.uid;
    let userName = event.data.displayName;

    return admin.firestore()
    .collection("users")
    .doc(userId)
    .set({
        name: userName,
        city: "",
        rating: 0
    });
});

Upvotes: 2

Related Questions