Tsukinose
Tsukinose

Reputation: 5

Don't want to overwrite the document if it already exists

This would overwrite it.

firebase.firestore().collection('test_collection').doc(this.id).set({
 body: this.body,
}, { merge: true })

{merge: true} didn't change whether it was there or not.

Upvotes: 0

Views: 254

Answers (2)

Dharmaraj
Dharmaraj

Reputation: 50920

In VueJS you can create a method like this to check existence of a document and use it in multiple components by passing as props if needed.

methods: {
    async checkExistence (collectionId, docId) {
        const docSnapshot = await admin.firestore().collection(collectionId).doc(docId).get()
        return docSnapshot.exists
    },
    async updateDocument (collectionId, docId, data) {
        // Check if doc exists
        if (await checkExistence(collectionId, docId)) {
          //exists, update 
        } else { ... }
    }
}

Upvotes: 0

Zero
Zero

Reputation: 133

{merge: true} is used to merge two object but overwrites props.

You have tu manually check if the doc exists:

firebase.firestore().collection('test_collection')
   .doc(this.id)
   .get()
   .then(docSnapshot => {
      if(!docSnapshot.exists)
         docSnapshot.ref.set({body: this.body})
   })

Upvotes: 1

Related Questions