简体   繁体   中英

Check an event type of currently affected document in firestore

Is there a way to check what was happened with currently affected document in Firestore collection?
Was it updated or it has created a new document?

For example to create a new document we can use this:

await db.collection('products').doc('xbox').set({ price: 300 });

I would like to get a feedback event for 2 following scenarios:

  1. Creating a new document
    Given there is no document in products collection with a document id xbox
    Then it would create a new one.

  2. Updating an existing document
    Given there is already an existing document with an id xbox .
    Then it should update it.

The question is:
How to get that info if it was created or updated ?

Real-life example when listening to Firestore

For example when listening to a realtime firestore updates, we can get that info like so:

db.collection('products').onSnapshot(snapshot => {
  snapshot.docChanges().forEach(change => {
    // Document write mode:
    console.log(change.type) // could be: added, modified, removed
  })
})

Is there something similiar tp change.type when modifying a document in firestore without actually listening to it but only using .set() ?

The set() just returns Promise<void> so you cannot check if document is new or existing document was updated using that. You'll have to check for document's existence before using set() .

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