简体   繁体   中英

How do I write a cloud function which creates a user in the Firestore database once a new user gets authenticated?

So far I have written the following code:

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

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

exports.addAccount = functions.auth.user().onCreate((event) => {
  const user = event.data; // The firebase user
  const id = user.uid;

  return admin
    .database()
    .ref("/users/" + id)
    .set("ok");
});

The idea here is to execute a cloud function once a new user gets created. As this happens, I want to create a new node in the Firestore database. Under the 'users' collection I want to add a document with the uid, which contains a bit of information, in this case a String that says 'ok'.

When deploying this function it produces an error. How exactly should I go about creating it?

The admin.database() returns the Realtime Database service. To use Firestore, use firebase.firestore() . Try refactoring the code as shown below:

exports.addAccount = functions.auth.user().onCreate((event) => {
  const user = event.data; // The firebase user
  const id = user.uid;

  return admin
    .firestore()
    .collection("users")
    .doc(id)
    .set({ uid: id, ...user });
});

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