【问题标题】:Referencing a new document created in Firestore引用在 Firestore 中创建的新文档
【发布时间】:2020-10-07 01:22:34
【问题描述】:

当我添加一个新文档时,如何引用新创建的文档的数据属性?

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

// Add a new document with a generated id.
let addDoc = db.collection('cities').add({
  name: 'Tokyo',
  country: 'Japan'
}).then(ref => {
  console.log('Added document with ID: ', ref.id);
  console.log(ref.data()); // << Errors!
});

【问题讨论】:

  • 为什么要以这种方式访问​​数据?你有它:{name: 'Tokyo', country: 'Japan'}
  • 在这种特定情况下,文档的数据将与您已经传递给add()的对象完全相同。您可以只存储对该对象的引用,而不是尝试再次读取它。你期待不同的东西吗?如果是这样,你能解释一下你想在这里做什么吗?

标签: javascript node.js google-cloud-firestore


【解决方案1】:

Ref 只是一个指向 firebase.firestore.DocumentReference 类型的数据库位置的指针,它没有 data() 方法。你可以这样做:

const admin = require('firebase-admin');

admin.initializeApp({
  credential: admin.credential.applicationDefault()
});

const db = admin.firestore();

let data = {
  name: 'Tokyo',
  country: 'Japan'
};

//Adding data (name: 'Tokyo', country: 'Japan')
let setDoc = db.collection('cities').add(data).then(ref => {
  console.log('Added document with ID: ', ref.id);

  // Retrieving the data from the recently created document.
  return db.collection('cities').doc(ref.id).get()
        .then(doc => {
           if (!doc.exists) {
             console.log('No such document!');
           } else {
             console.log('Document data:', doc.data());
           }
        })
       .catch(err => {
          console.log('Error getting document', err);
       });

}).catch(err => {
 console.log('Error adding the data',err);
});

您将检索到Document data: { name: 'Tokyo', country: 'Japan' },这与您刚刚在上面添加的数据相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2021-04-02
    • 2020-03-03
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多