【问题标题】:Firebase db with vuejs : default.collection is not a function带有 vuejs 的 Firebase 数据库:default.collection 不是函数
【发布时间】:2021-06-10 13:53:41
【问题描述】:

我正在使用VuejsFirebase 开始一个小项目。我正在尝试将 NamePrice 上传到 Firestore。我检查了他们的文档和一些教程,但我遇到了这个错误。

<div class="form-group">
      <v-btn v-on:click="saveData" class="btn btn-primary">Save data</v-btn>
</div>

import db from "../firebase";
export default {
  name: "products",
  props: {
    msg: String,
  },
  data() {
    return {
      aon: {
        Name: null,
        Price: null,
      },
    };
  },
  methods: {
    saveData() {
      db.collection("Products")
        .add(this.Product)
        .then((docRef) => {
          console.log("Document written with ID: ", docRef.id);
        })
        .catch((error) => {
          console.error("Error adding document: ", error);
        });
    },
  },
};

这是我的 firebase.js

import firebase from '@firebase/app';
import '@firebase/auth';
import '@firebase/firestore';

const fb = firebase.initializeApp({
    apiKey: "!!!!!!!!!!!",
    authDomain: "!!!!!!!!",
    databaseURL: "!!!!!!!",
    projectId: "!!!!!!",
    storageBucket: "!!!!!!!",
    messagingSenderId: "!!!!!!!",
    appId: "!!!!!!!!!",
    measurementId: "!!!!!!!!!!!!"
});
const db = firebase.firestore();
export default firebase;
export {db,fb} ;

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore vuetify.js


    【解决方案1】:

    根据文档herehere,您需要像这样使用.set().add().update().doc() 方法。

    当您使用set() 创建文档时,您必须指定要创建的文档的 ID。例如:

    await db.collection('cities').doc('new-city-id').set(data);
    

    让 Cloud Firestore 为您自动生成一个 ID。您可以拨打add()

    // Add a new document with a generated id.
    const res = await db.collection('cities').add({
      name: 'Tokyo',
      country: 'Japan'
    });
    
    console.log('Added document with ID: ', res.id);
    

    在某些情况下,使用自动生成的 ID 创建文档引用会很有用,然后再使用该引用。对于这个用例,您可以致电doc()

    const newCityRef = db.collection('cities').doc();
    
    // Later...
    const res = await newCityRef.set({
      // ...
    });
    

    要更新文档的某些字段而不覆盖整个文档,请使用update() 方法:

    const cityRef = db.collection('cities').doc('DC');
    
    // Set the 'capital' field of the city
    const res = await cityRef.update({capital: true});
    

    【讨论】:

      【解决方案2】:

      首先,您没有初始化 Firebase 应用。这样做:

      //firebase.js
      
      const db = firebase.initializeApp(fb)
      export {db.firestore(),fb}
      

      然后在您写的产品页面或组件上:

      //products.vue
      
      db.collection("Products").add(this.Product)...
      

      this.Product 对象不存在,所以它应该是this.aon

      //products.vue
      
      db.collection("Products").add(this.aon)...
      

      欲了解更多信息:https://firebase.google.com/docs/firestore/quickstart

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-03
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-03
        • 2017-11-15
        相关资源
        最近更新 更多