代码之家  ›  专栏  ›  技术社区  ›  ofey

如何在中获取新创建的Firestore文档的IDVue.js?

  •  0
  • ofey  · 技术社区  · 7 年前

    当我从表单“创建”数据时,我可以将其发送到数据库,但当我尝试更新本地对象数组时,没有文档id,因为这是由firebase在创建新文档时创建的。那么,如何在不必从数据库获取所有数据的情况下检索新的文档id呢?

    这一定有规律。我唯一能想到的就是 '全部'

    有没有办法让id传回新创建文档的组件?

    <template lang="html">
      <div class="crud">
        <h1>I am the crud component</h1>
        <div v-for="item in peoples" :key="peoples.id" class="peoples">
          <h3>name: {{ item.name}} age: {{ item.age}} id: {{ item.id }} <button @click="deletePeople(item.id)">delete</button> </h3>
        </div>
        <form @submit.prevent="addPerson()">
          <div>
            <label for="name">Name:</label>
            <input type="text" name="name" v-model="name">
          </div>
          <div>
            <label for="age">Age:</label>
            <input type="number" name="age" v-model="age">
          </div>
          <div>
            <button>add person to database</button>
          </div>
       </form>
      </div>
    </template>
    
    <script>
    import db from '@/firebase/init'
    
    export default {
      name: 'Crud',
      data(){
        return {
          msg: 'hello all',
          peoples: [],
          name: null,
          age: null
        }
      },
      methods:{
        addPerson(){
          console.log('addPerson() method running');
          console.log('person: ' + this.name);
          db.collection('people').add({
            name: this.name,
            age: this.age
          }).then(() => {
    
            db.collection('people').get().then(snapshot => {
              this.peoples = []
              snapshot.forEach(doc => {
                // console.log(doc.data(), doc.id);
                let people = doc.data()
                people.id = doc.id
                this.peoples.push(people)
              })
            })
    
            // console.log('push to local data');
            // this.peoples.push({ name: this.name, age: this.age})
          })
        },
    

    任何帮助都将不胜感激,

    1 回复  |  直到 7 年前
        1
  •  8
  •   niclas_4    7 年前
    // Add a new document with a generated id.
    db.collection("cities").add({
        name: "Tokyo",
        country: "Japan"
    })
    .then(function(docRef) {
        console.log("Document written with ID: ", docRef.id);
    })
    .catch(function(error) {
        console.error("Error adding document: ", error);
    });
    

    https://firebase.google.com/docs/firestore/manage-data/add-data

    在这里你可以简单地说 this.lastID = docRef.id .then() 在那之后,您可以简单地读取带有ID的文档 lastID .

    推荐文章