【问题标题】:Copying documents from one collection to another in cloud firestore在 Cloud Firestore 中将文档从一个集合复制到另一个集合
【发布时间】:2021-02-24 23:47:35
【问题描述】:

由于云 Firestore 中没有“移动”或“重命名”命令,我每天早上 6 点(英国时间)尝试将所有文​​档从一个集合复制到另一个集合。到目前为止,我已经想出了这段代码,但不确定如何获取 resID,然后在将原始文档保存在另一个集合中后将其删除:

exports.scheduledFunctionCrontab = functions.pubsub.schedule('0 6 * * *')
    .timeZone('Europe/London') // Is this correct?
    .onRun((context) => {
    var dateObj = new Date();
    var month = dateObj.getUTCMonth() + 1; //months from 1-12
    var day = dateObj.getUTCDate();
    var year = dateObj.getUTCFullYear();
    console.log(`This function ran at ${Date.now}!`);
    db.collection("Restaurants/${**resID**}/openorders").get().then(query => {
       query.forEach(function(doc) {
          var promise = firestore.collection("Restaurants/${**resID**}/closed/${year}/${month}/${day}/closed).doc(doc.data().orderID).set(doc.data());
// How I delete this document here?
       });
    })
    .catch((error)=>{
        console.log('Failure:', e);
        console.log(`This function ran with ERROR at ${Date.now}!`);
      });
    return null;
  });
  

【问题讨论】:

  • 您在寻找doc.ref.delete()吗?
  • 您想将所有日常文档转移到另一个集合吗?
  • @FrankvanPuffelen 也许他正在寻找如何获得resId
  • 谢谢。是的,我正在研究如何在许多 redID 之间进行迭代。我试图让它变得大胆,因此他们周围的 astricks。

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


【解决方案1】:

要遍历所有名为 openorders 的集合,您可以使用 collection group query

然后要获取每个openorders 文档的父文档,您可以使用refparent 属性。

比如:

db.collectionGrouo("openorders").get().then(query => {
   query.forEach(function(doc) {
      let resID = doc.ref.parent.parent.id;
      ...
   });
})

对于这类事情,我始终建议将参考文档放在手边,以DocumentSnapshot 开头。

【讨论】:

  • 这太棒了。删除了我的解决方案,因为这是处理问题的更好方法。我不知道您可以调用 DocumentReference 和 CollectionReference 的父属性。对我来说确实改变了游戏规则。
  • 很高兴听到@KasualDev ? 向上导航父链有时有点令人困惑(每当我这样做时,我最终都会数数我的手指),但这是在集合中查询的唯一方法那一刻。
  • 非常感谢弗兰克!对于在此问题及其答案方面获得帮助的其他人,请为他们俩投票。
猜你喜欢
  • 2020-09-12
  • 2022-01-19
  • 2021-12-04
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 2021-10-23
相关资源
最近更新 更多