javascript - 关于将文档增量添加到 Firestore React Native
问题描述
我目前正在尝试逐步将文档添加到 Firestore。因此,在文档 0 之后,添加了文档 1。在文档 1 之后,添加了文档 2。但是,我无法完成这项工作。我尝试了一个while循环,但我认为我陷入了无限循环。
具体来说,我正在尝试添加文档 m0、m1、m2 等。这是我尝试使用 while 循环:
var idofmeal = 0;
var docexists = null;
const mealref = db.collection('entirelog').doc(this.state.docid).collection('meals').doc("m" + idofmeal.toString());
mealref.get().then(docSnapshot => {
if(docSnapshot.exists) {
docexists = true;
idofmeal = idofmeal + 1;
} else {
docexists = false;
db.collection('entirelog')
.doc(this.state.docid)
.collection('meals')
.doc('m' + (idofmeal).toString())
.set({
id: this.state.idofmeal,
protein: this.state.protein,
carbohydrate: this.state.carbohyrdate,
foodname: this.state.foodname,
durl: downloadurl,
photoid: randomid,
});
}
});
while(docexists) {
const mealref = db.collection('entirelog').doc(this.state.docid).collection('meals').doc("m" + idofmeal.toString());
mealref.get().then(docSnapshot => {
if (docSnapshot.exists) {
docexists = true;
idofmeal = idofmeal + 1;
} else {
docexists = false;
db.collection('entirelog')
.doc(this.state.docid)
.collection('meals')
.doc('m' + (idofmeal).toString())
.set({
id: this.state.idofmeal,
protein: this.state.protein,
carbohydrate: this.state.carbohyrdate,
foodname: this.state.foodname,
durl: downloadurl,
photoid: randomid,
});
}
});
}
逻辑似乎真的很低效,我想知道是否有更清洁的方法来做到这一点。
-----------------------------------------新编辑我也试过:
const mealref = db.collection('entirelog').doc(this.state.docid).collection('meals').doc("m" + this.state.idofmeal.toString());
mealref.get().then(docSnapshot => {
if(!(docSnapshot.exists)) {
db.collection('entirelog')
.doc(this.state.docid)
.collection('meals')
.doc('m' + (this.state.idofmeal).toString())
.set({
id: this.state.idofmeal,
protein: this.state.protein,
carbohydrate: this.state.carbohyrdate,
foodname: this.state.foodname,
durl: downloadurl,
photoid: randomid,
});
} else {
var collection = db.collection('entirelog').doc(this.state.docid).collection('meals');
var query = collection.orderBy(firebase.firestore.FieldPath.documentId(), "desc").limit(1);
query.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id);
});
});
}
});
但是,我收到此错误“[未处理的承诺拒绝:FirebaseError:查询需要索引。您可以在此处创建它:”如何添加此索引?
解决方案
如果我理解正确,当文档按 ID 排序时,您想确定集合中最后一个文档的 ID。如果是这种情况,您可以这样做:
var collection = db.collection('entirelog').doc(this.state.docid).collection('meals');
var query = collection.orderBy(firebase.firestore.FieldPath.documentId(), "desc").limit(1);
query.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id);
});
});
如果多个用户/应用程序实例可能同时写入此集合,您需要确保他们不会使用事务和/或安全规则覆盖彼此的新餐点。