add a property to a created object (Firebase Functions)

I'm hooking to the creation of objects on a specific collection (orders) I need to add a new property to the object before it's saved, not returning anything, to no avail.

I have looked at the documentation at https://firebase.google.com/docs/reference/functions/functions.firestore.DocumentBuilder#writing_data but it's for onUpdate so it doesn't work as i intend it.

exports.createOrder = firestore.document('orders/{orderId}').onCreate((snap, context) => {
  const newOrder = snap.data()
  console.log('triggered', newOrder)
  const orderId = randomize('A0', 10)
  console.log({ orderId })
  return newOrder.ref.set({ orderId }, { merge: true })
  //newOrder.ref.set is undefined
  return newOrder.set({ orderId }, { merge: true })
  //newOrder.set is undefined
})

Upvotes: 1

Views: 483

Answers (2)

Stéphane de Luca
Stéphane de Luca

Reputation: 13563

Capture the creation event with the onCreate() and use the snap.ref.update() to add your extra properties like so:


// === Classified ad moderation: add clearForSale to null

exports.classifiedAdClearForSaleSettoNull = functions.firestore
    .document("classifiedAds/{id}")
    .onCreate((snap/*, context*/) => {

    try {
        snap.ref.update({"clearForSale":null});
    }
    catch(e) {
        console.error(`Error: ${e}`)
    }

    return null
})

In this snipet, I add the property clearForSale with the null value each time a classified ad is created in the ClassifiedAds collection.

This enables for the moderation dashboard to capture the latest ads to be moderated. When the moderator accept the dd, the dashboard turn null to true and add additional properties like the moderator ID and the date he accepted it.

Conversely, update with false whenever the ad is not accepted.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317362

snap.data() returns a raw JavaScript object whose properties contain the values of the fields in the document. It does not contain a property called ref (unless you had a document field also called ref).

If you need to write back to the document that changed, use the DocumentReference type object provided in snap.ref. See also the API documentation for the DocumentSnapshot type object passed to the function.

snap.ref.set(...)

Upvotes: 1

Related Questions