【问题标题】:Add document if query returns 0 documents如果查询返回 0 个文档,则添加文档
【发布时间】:2018-07-05 15:37:38
【问题描述】:

因此,如果我运行的查询未返回任何结果,我会尝试将文档添加到集合中。我将查询放在下面,但没有用于检查结果查询的长度或大小的运算符。我该怎么做?

这里是查询:

this.monthCollection = this.afs.collection('users').doc(this.auth.getUserId()).collection('months', ref => {
  return ref.where('endTimestamp', '>=', moment().unix()).limit(1);
});

如果该查询没有返回任何文档,那么我需要运行 createNewMonth(); 以添加到月份集合中。这里是 createNewMonth` 方法

createNewMonth() {
    let date = new Date(), y = date.getFullYear(), m = date.getMonth();
    let firstDay = new Date(y, m, 1);
    let lastDay = new Date(y, m + 1, 0);

    let newMonth = {
      categories: [],
      endTimestamp: moment(lastDay).unix(),
      name: this.getMonthNameFromTimestamp(moment().unix()),
      startTimestamp: moment(firstDay).unix(),
      totalSpent: 0
    }
    return this.monthCollection.add(newMonth);
  }

如果我使用.then() 或者是否需要在查询之外,有没有办法可以在查询中执行此操作?

编辑:所以我找到了一种方法来创建一个,但它每次都创建 2 而不仅仅是一个。这是代码。

this.currentMonth = this.monthCollection.snapshotChanges().map(snapshot => {
      if (snapshot.length <= 0) {
        this.createNewMonth();   <---- here is what I added, it creates 2
      }

      return snapshot.map(doc => {
        const data = doc.payload.doc.data();
        data.id = doc.payload.doc.id;
        this.currentMonthId = doc.payload.doc.id;
        this.currentMonthTotalSpent = doc.payload.doc.data().totalSpent;

        this.expenseCollection = this.monthCollection.doc(doc.payload.doc.id).collection('expenses');
        this.expenses = this.expenseCollection.snapshotChanges().map(snapshot => {
          return snapshot.map(doc => {
            const data = doc.payload.doc.data();
            data.id = doc.payload.doc.id;
            return data;
          });
        });
        return data;
      });
    });

【问题讨论】:

    标签: javascript angular ionic-framework google-cloud-firestore


    【解决方案1】:

    在运行 .snapshotChanges() 时,在 angularfire2 中,您可以检查是否找到这样的结果:

    this.dbRef.snapshotChanges().subscribe(doc => {
    
    if(doc.payload.exists)
    {
    ///Do something with the returned data
    }
    else
    {
    this.createNewMonth();
    }
    
    });
    

    在查找.valueChanges() 时,如果没有找到数据,则'doc' 将返回为空:

    this.dbRef.valueChanges().subscribe(doc => {
    
    if(doc)
    {
    ///Do something with the returned data
    }
    else
    {
    this.createNewMonth();
    }
    
    });
    

    【讨论】:

    • 不幸的是,这不适用于我得到的几个月你能在示例代码的上下文中写这个吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多