Javascript 如果查询返回0个文档,则添加文档

Javascript 如果查询返回0个文档,则添加文档,javascript,angular,ionic-framework,google-cloud-firestore,Javascript,Angular,Ionic Framework,Google Cloud Firestore,因此,如果我运行的查询没有返回结果,我将尝试将文档添加到集合中。我将查询放在下面,但没有用于检查结果查询的长度或大小的运算符。我该怎么做 以下是查询: this.monthCollection = this.afs.collection('users').doc(this.auth.getUserId()).collection('months', ref => { return ref.where('endTimestamp', '>=', moment().unix()).l

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

以下是查询:

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;
      });
    });
this.currentMonth=this.monthCollection.snapshotChanges().map(快照=>{
if(snapshot.length{
返回snapshot.map(doc=>{
const data=doc.payload.doc.data();
data.id=doc.payload.doc.id;
返回数据;
});
});
返回数据;
});
});

在angularfire2中运行
时。snapshotChanges()
您可以检查是否找到如下结果:

this.dbRef.snapshotChanges().subscribe(doc => {

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

});
查找
.valueChanges()
时,如果未找到任何数据,则“doc”将返回为null:

this.dbRef.valueChanges().subscribe(doc => {

if(doc)
{
///Do something with the returned data
}
else
{
this.createNewMonth();
}

});

不幸的是,这与我得到的月数不符。您能在示例代码的上下文中编写这篇文章吗?