Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
Firebase Cloud Function. Create documents in sub-collection of specific collections

here's the basic premise of what im trying to accomplish here. if a user ask a question about a product i want to send a notification to other users who currently own that product. basically saying "hey, so and so has a question about this product. maybe you can help since you own it already"

each userProfile collection has a subcollection called 'notify' where notifications are stored for various things. what i need to do is sort through the userProducts and find every user who owns the product and then create a notification post in only the notify sub-collections for those specific users who own that product.

here is the basic code. the first bit works in that it does return an array of userIDs who own that product. where im struggling now is getting it to create a new doc in the Notify sub-collection for just those specific users. is this possible to do?

exports.Questions = functions.firestore
.document("/userPost/{id}")
.onCreate(async (snap, context) => {
const data = snap.data();

if (data.question == true) {
  const userProducts = await db
    .collection("userProducts")
    .where("product", "==", data.tag)
    .get();

  const userData = userProducts.docs.map((doc) => doc.data().userId);



  await db
    .collection("userProfile")
    .where("userId", "in", userData)
    .get()
    .then((querySnapshot) => {
      return querySnapshot.docs.ref.collection("notify").add({
        message: "a user has asked about a product you own",
      });
    });
 });
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your current solution is on the right track, but improvements can be made.

  • Use a protection pattern for data.question == true .
  • You don't need to get userProfile/<uid> as you are not using its content.
  • When changing multiple documents at once, you should consider batching them together to simplify error handling.
  • ref.add(data) is shorthand for ref.doc().set(data) that you can use in batch writing to create new documents.
 exports.Questions = functions.firestore .document("/userPost/{id}") .onCreate(async (snap, context) => { const data = snap.data(); if (!data.question) { console.log("New post not a question. Ignored.") return; } const userProducts = await db .collection("userProducts") .where("product", "==", data.tag) .get(); const userIds = userProducts.docs.map(doc => doc.get("userId")); // more efficient than doc.data().userId // WARNING: Limited to 500 writes at once. // If handling more than 500 entries, split into groups. const batch = db.batch(); const notificationContent = { message: "a user has asked about a product you own", }; userIds.forEach(uid => { // creates a ref to a new document under "userProfile/<uid>/notify" const notifyDocRef = db.collection(`userProfile/${uid}/notify`).doc(); batch.set(notifyDocRef, notificationContent); }); await batch.commit(); // write changes to Firestore });

Note: There is no special handling here for when nobody has bought a product before. Also consider pinging the product owner.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda