【问题标题】:Firestore, get the document ID using snapshotFirestore,使用快照获取文档 ID
【发布时间】:2020-12-16 11:41:25
【问题描述】:

我正在尝试从 firestore 获取集合数据,并将该数据保存为 JSON 格式,现在我可以同时执行这两项操作,并且每次更新我的列表时,问题是它没有显示ID 字段,因此所有遭受更改的集合都将在没有任何文档 ID 的情况下保存。我尝试了附件中建议的一些解决方案,但它根本不起作用。 任何可以帮助我的建议或想法。

Get document id firestore angular

How to get firestore document ID from document snapshot?

const fs =require('fs');
const db = admin.firestore();
var Notebook = db.collection('Notebook').where('itemCFE', '==', '1')
.onSnapshot(querySnapshot => {
  querySnapshot.docChanges().forEach(change => {
    if (change.type === 'modified'){
       console.log('update done',JSON.stringify(change.doc.data()));
       let data =JSON.stringify(change.doc.data());
       fs.writeFileSync('test.json', data, (err) => {
       if (err) throw err;
       console.log('Data Written to file');
       })
     }
   if (change.type === 'removed'){
      console.log('update done',change.doc.data());
   }
 });
});

【问题讨论】:

    标签: node.js json firebase google-cloud-firestore snapshot


    【解决方案1】:

    文档总是一个 ID。在你的 forEach 循环中,每个 change 是一个 DocumentChange 对象。您可以通过change.doc.id获取文档的ID。

    【讨论】:

    • 我已经尝试过了,得到了下一个错误TypeError: change.doc.id is not a function
    • 你在“id”后面加括号吗? id 是 DocumentSnapshot 对象change.doc 上的对象属性,而不是函数。您可以从 DocumentSnapshot 的文档中看到。 googleapis.dev/nodejs/firestore/latest/DocumentSnapshot.html
    • 是的,我把括号 console.log('update done',JSON.stringify(change.doc.id()));
    • 不要那样做。它是一个属性,而不是一个方法。只需change.doc.id
    【解决方案2】:

    如果我理解正确的话,除了通过DocumentChange通过change.doc.data()获取doc的数据,你还想获取doc ID。

    您需要执行change.doc.id,因为DocumentChangedoc 属性返回QueryDocumentSnapshot

    【讨论】:

    • 我已经尝试过了,得到了下一个错误TypeError: change.doc.id is not a function
    • 你能给出产生这个错误的确切代码吗?
    • 当然D:\Upload JSON\Prueba\index.js:33 console.log('update done',JSON.stringify(change.doc.id())); ^ TypeError: change.doc.id is not a function at D:\Upload JSON\Prueba\index.js:33:60 at Array.forEach (<anonymous>) at D:\Upload JSON\Prueba\index.js:31:30
    猜你喜欢
    • 2019-08-02
    • 2020-10-12
    • 1970-01-01
    • 2018-03-19
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 2019-03-22
    相关资源
    最近更新 更多