简体   繁体   中英

Using set to only update a subset of write properties in a Firestore transaction

Is it possible to use set (within the context of a transaction) to create a document with some object, but only update it with a subset of properties?

For example, I have a use case where I'd like to create or update a document, but in the update case only certain fields should be merged. In the code below, created should only be written on document creation (and not on update).

I've tried mergeFields in SetOptions which I thought would only apply to the update case, but seems to apply to the write case as well and causes created to be omitted when creating the document.

If that's the intended behaviour of SetOption is there another way to achieve this?

t.set(docRef, 
  {
    name: 'Alice',
    updated: admin.firestore.FieldValue.serverTimestamp(),
    created: admin.firestore.FieldValue.serverTimestamp(),
  },
  { mergeFields: ['name', 'updated'] });

Node.js Admin SDK 9.2.0

Seems like yourtransaction will first have to read the document with get() to create or update, then make a decision about what to pass to set() in order to make sure the document contains the correct fields. A single set() cannot make this decision for you. So, something like:

const snap = await t.get(docRef)
if (snap.exists) {
    t.update(docRef, ...)
}
else {
    t.create(docRef, ...)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM