mcd
mcd

Reputation: 726

Batched write to Firebase Cloud Firestore failed due to wrong type

I'm trying to execute a batched write to my database. However there seems to be a problem with data[] because I get this error:

FirebaseError: Expected type 't', but it was: a custom e object

The Code:

<template>
  <div>
    <v-btn @click="setData()">
      Write to Firestore
    </v-btn>
    <router-view/>
  </div>
</template>

<script>
 import { db } from '@/firebase'

export default {
  methods: {
    setData() {
      
    var data = 
      [
        { 
          'title':'Ipsum lorem',
          'description':'Some text...',
          'color':'#03A9F4',
          'meta': 
            { 
              'docID':'',
              'createdBy':'', 
            }
        },
        { 
          'title':'Loren ipsum',
          'description':'Some more text...',
          'color':'#06A1F3',
          'meta': 
            { 
              'docID':'',
              'createdBy':'', 
            }
        }
      ]

      var batch = db.batch()
      data.forEach((doc) => {
        var dbRef = db.collection('teams').doc('team01').collection('templates')
        batch.set(dbRef, doc)
      })
      batch.commit().then(function() {
        return console.log("done")
      });
    }
  }
}
</script>

In my file data[] contains more objects than shown here. They are below the limit of 500. This is done in my Vue.js app using Vuetify.

  1. How can I solve this problem?
  2. How can I add the id/reference of each document created and put it in meta.docID? I can't get this to work with batched writes.

Any help is appreciated, thank you!

Upvotes: 1

Views: 2289

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

Your dbRef is a CollectionReference object:

var dbRef = db.collection('teams').doc('team01').collection('templates')

It's not valid to pass a CollectionReference to set():

batch.set(dbRef, doc)   // this isn't valid

As you can see from the API documentation, set() requires a DocumentReference as its first argument instead, so you will need to identify a document to write in order to call it. This means you'll need to figure out a unique ID of a document to write here. For example:

var dbRef = db
    .collection('teams')
    .doc('team01')
    .collection('templates')
    .doc("what-is-your-document-id?")

If you need a random document ID, you can simply provide no arguments in the call to doc():

var dbRef = db
    .collection('teams')
    .doc('team01')
    .collection('templates')
    .doc()

Upvotes: 4

Related Questions