add a property to a created object (Firebase Functions)

北城余情 提交于 2021-01-29 09:19:36

问题


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
})

回答1:


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(...)


来源:https://stackoverflow.com/questions/58312876/add-a-property-to-a-created-object-firebase-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!