简体   繁体   English

获取 id 和删除文档 Vuejs Firestore 的问题

[英]problem getting id and deleting document Vuejs Firestore

I am creating site for my store and learning Vue js at the same time.我正在为我的商店创建网站并同时学习 Vue js。 I'm having a problem with getting product id from firestore and being able to delete product.我在从 Firestore 获取产品 ID 并能够删除产品时遇到问题。 When i create a new product in console id doesn't come out either, got this message (Document written with ID: undefined) I'm using Vue js 3 and Firebase 9当我在控制台 ID 中创建新产品时,也没有出现此消息(使用 ID 编写的文档:未定义)我正在使用 Vue js 3 和 Firebase 9

I have this on main.j我在 main.j 上有这个

const dataBase = collection(db, "products");

and this on products.js这在 products.js

<script>
import { dataBase } from '../main';
import { addDoc, onSnapshot, doc, deleteDoc } from "firebase/firestore";

export default {
  name: "Products",
  props: {
    msg: String
  },
  data() {
    return {
      products: [],
      product: {
        name: '',
        detail: '',
        price: '',
        brand: '',
        category: ''
      }
    }
  },
  methods: {
    saveData() {
      try {
        const docRef = addDoc(dataBase, this.product);
        console.log("Document written with ID: ", docRef.id);
        this.reset();
      } catch (e) {
        console.error("Error adding document: ", e);
      }
    },
    reset() {
      Object.assign(this.$data, this.$options.data.apply(this));
    },
    deleteProduct(doc) {
      deleteDoc(doc(dataBase, doc.id));
    }
  },
  created() {
    onSnapshot(dataBase, (snapshot) => {
      snapshot.docs.forEach((doc) => {
        this.products.push({ ...doc.data(), id: doc.id })
      })
    });
  }
};
</script>

The "Document written with ID: undefined" output is because theaddDoc function is an asynchronous operation and thus returns a Promise<DocumentReference> . “使用 ID 编写的文档:未定义” output 是因为addDoc function是异步操作,因此返回Promise<DocumentReference> You'll have to either await its result, or use then :您必须await其结果,或使用then

addDoc(dataBase, this.product).then((docRef) => {
  console.log("Document written with ID: ", docRef.id);
  this.reset();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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