【发布时间】: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