问题
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