因此,如果我运行的查询未返回任何结果,则我尝试将文档添加到集合中。我将查询放在下面,但是没有运算符可用于检查结果查询的长度或大小。我该怎么办?
以下是查询:
this.monthCollection = this.afs.collection('users').doc(this.auth.getUserId()).collection('months', ref => {
return ref.where('endTimestamp', '>=', moment().unix()).limit(1);
});
如果该查询未返回任何文档,那么我需要运行createNewMonth();
以添加到months集合中。这是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;
});
});
答案 0 :(得分:0)
在运行.snapshotChanges()
的angularfire2中,您可以检查是否找到了这样的结果:
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();
}
});