在snapshotChanges中添加文档会添加2个文档

时间:2018-07-05 18:50:56

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

因此,如果查询返回0个文档,我将尝试添加一个文档。我已经得到它来创建新文档,但是由于某种原因它却创建了2个?我有办法将其限制为仅创建一个吗?

这是方法

this.currentMonth = this.monthCollection.snapshotChanges().map(snapshot => {
  if (snapshot.length <= 0) {
    this.createNewMonth(); <---- THIS GETS CALLED TWICE
  }
  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;
  });
});

编辑:当应用打开时,我需要检查一下Firestore中是否有一个结束时间戳大于当前时间的月份对象。如果不是这种情况(这意味着它是一个新的月份),我需要创建一个新的月份。我将创建新月份的方法放在下面,以供参考。我遇到的问题是创建了2个文档,而我只需要一个。

  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
    }
    this.monthCollection.add(newMonth);
  }

编辑2:monthCollection

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

编辑3:所以我将检查从快照中移出,又移到了另一个检查中,但它仍在创建2个文档。您在下面看到的内容位于其他代码之上。

this.afs.collection('users').doc(this.auth.afAuth.auth.currentUser.uid).collection('months').ref.where('endTimestamp', '>=', moment().unix()).get().then((result) => {
      if (result.empty || result.size <= 0) {
        this.createNewMonth();
      }
    });

1 个答案:

答案 0 :(得分:0)

预计快照侦听器将触发两次。

第一次会给您集合的初始内容。然后,在createNewMonth()函数中,将一个新文档添加到同一集合中。然后,快照侦听器将再次触发集合的更新内容,该集合现在包含您刚刚添加的文档。

您应该知道,侦听器函数接收到的role="radio"上没有length属性。这是无效的代码:

snapshot

if (snapshot.length <= 0) { this.createNewMonth(); } QuerySnapshot对象。如果您想知道该快照中有多少个文档,请使用其size属性或empty属性。

此外,如果您不想持续监视集合中的更改,请考虑在集合引用上使用get()而不是像现在那样添加侦听器。它将一次给您一组结果。

相关问题