Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda