是否可以使用新的Firebase数据库Cloud Firestore来计算一个集合有多少项?
如果是,我该怎么做?
是否可以使用新的Firebase数据库Cloud Firestore来计算一个集合有多少项?
如果是,我该怎么做?
当前回答
对于大量的收藏,要仔细计算文件的数量。如果你想为每个收集都有一个预先计算好的计数器,那么firestore数据库就有点复杂了。
这样的代码在这种情况下不起作用:
export const customerCounterListener =
functions.firestore.document('customers/{customerId}')
.onWrite((change, context) => {
// on create
if (!change.before.exists && change.after.exists) {
return firestore
.collection('metadatas')
.doc('customers')
.get()
.then(docSnap =>
docSnap.ref.set({
count: docSnap.data().count + 1
}))
// on delete
} else if (change.before.exists && !change.after.exists) {
return firestore
.collection('metadatas')
.doc('customers')
.get()
.then(docSnap =>
docSnap.ref.set({
count: docSnap.data().count - 1
}))
}
return null;
});
原因是每个云防火墙触发器都必须是幂等的,正如防火墙文档所示:https://firebase.google.com/docs/functions/firestore-events#limitations_and_guarantees
解决方案
因此,为了防止代码多次执行,您需要使用事件和事务进行管理。这是我处理大型收款柜台的特殊方式:
const executeOnce = (change, context, task) => {
const eventRef = firestore.collection('events').doc(context.eventId);
return firestore.runTransaction(t =>
t
.get(eventRef)
.then(docSnap => (docSnap.exists ? null : task(t)))
.then(() => t.set(eventRef, { processed: true }))
);
};
const documentCounter = collectionName => (change, context) =>
executeOnce(change, context, t => {
// on create
if (!change.before.exists && change.after.exists) {
return t
.get(firestore.collection('metadatas')
.doc(collectionName))
.then(docSnap =>
t.set(docSnap.ref, {
count: ((docSnap.data() && docSnap.data().count) || 0) + 1
}));
// on delete
} else if (change.before.exists && !change.after.exists) {
return t
.get(firestore.collection('metadatas')
.doc(collectionName))
.then(docSnap =>
t.set(docSnap.ref, {
count: docSnap.data().count - 1
}));
}
return null;
});
用例如下:
/**
* Count documents in articles collection.
*/
exports.articlesCounter = functions.firestore
.document('articles/{id}')
.onWrite(documentCounter('articles'));
/**
* Count documents in customers collection.
*/
exports.customersCounter = functions.firestore
.document('customers/{id}')
.onWrite(documentCounter('customers'));
如您所见,防止多次执行的关键是上下文对象中名为eventId的属性。如果函数对同一个事件处理了多次,那么事件id在所有情况下都是相同的。不幸的是,您的数据库中必须有“事件”集合。
其他回答
目前,firebase只允许服务器端计数,如下所示
const collectionRef = db.collection('cities');
const snapshot = await collectionRef.count().get();
console.log(snapshot.data().count);
请不要,这是为nodeJS
使用admin. keystore . fieldvalue . Increment增加一个计数器:
exports.onInstanceCreate = functions.firestore.document('projects/{projectId}/instances/{instanceId}')
.onCreate((snap, context) =>
db.collection('projects').doc(context.params.projectId).update({
instanceCount: admin.firestore.FieldValue.increment(1),
})
);
exports.onInstanceDelete = functions.firestore.document('projects/{projectId}/instances/{instanceId}')
.onDelete((snap, context) =>
db.collection('projects').doc(context.params.projectId).update({
instanceCount: admin.firestore.FieldValue.increment(-1),
})
);
在本例中,每次将文档添加到instances子集合时,我们都会增加项目中的instanceCount字段。如果该字段还不存在,它将被创建并增加到1。
增量在内部是事务性的,但如果需要更频繁地递增,则应该使用分布式计数器。
通常最好实现onCreate和onDelete而不是onWrite,因为你将调用onWrite进行更新,这意味着你在不必要的函数调用上花费了更多的钱(如果你更新了你的集合中的文档)。
这使用计数来创建数字唯一ID。在我的使用中,我将永远不会递减,即使需要ID的文档被删除。
在需要唯一数值的集合创建时
用一个文档指定一个集合appData,只设置.doc id 在firebase防火控制台中将uniqueNumericIDAmount设置为0 使用doc.data()。uniqueNumericIDAmount + 1作为唯一的数字id 更新appData收集uniqueNumericIDAmount与firebase.firestore.FieldValue.increment(1)
firebase
.firestore()
.collection("appData")
.doc("only")
.get()
.then(doc => {
var foo = doc.data();
foo.id = doc.id;
// your collection that needs a unique ID
firebase
.firestore()
.collection("uniqueNumericIDs")
.doc(user.uid)// user id in my case
.set({// I use this in login, so this document doesn't
// exist yet, otherwise use update instead of set
phone: this.state.phone,// whatever else you need
uniqueNumericID: foo.uniqueNumericIDAmount + 1
})
.then(() => {
// upon success of new ID, increment uniqueNumericIDAmount
firebase
.firestore()
.collection("appData")
.doc("only")
.update({
uniqueNumericIDAmount: firebase.firestore.FieldValue.increment(
1
)
})
.catch(err => {
console.log(err);
});
})
.catch(err => {
console.log(err);
});
});
其中一个快速省钱的技巧是:-
创建一个文档并在firestore中存储一个“count”变量,当用户在集合中添加新文档时,增加该变量,当用户删除一个文档时,减少变量。如。 updateDoc(doc(db, "Count_collection", "Count_Doc"), {count: increment(1)});
注:计数用(-1)递减,用(1)递增
如何节省金钱和时间:-
你(firebase)不需要循环通过集合,浏览器也不需要加载整个集合来计数文档的数量。 所有的计数都保存在一个名为“count”或其他变量的文档中,因此使用不到1kb的数据,并且它只在firebase firestore中使用1次读取。
没有直接的选择。不能执行db.collection("CollectionName").count()。 下面是查找集合中文档数量的两种方法。
1:-得到集合中的所有文件,然后得到它的大小。(不是最好的解决方案)
db.collection("CollectionName").get().subscribe(doc=>{
console.log(doc.size)
})
通过使用上述代码,您的文档读取的大小将等于集合中的文档大小,这就是为什么必须避免使用上述解决方案的原因。
2:-创建一个单独的文档与在您的集合,将存储在集合中的文件的数量计数。(最佳解决方案)
db.collection("CollectionName").doc("counts")get().subscribe(doc=>{
console.log(doc.count)
})
上面我们创建了一个带有名称计数的文档来存储所有计数信息。您可以通过以下方式更新计数文档:—
在文档计数上创建一个触发器 在创建新文档时,增加counts文档的count属性。 删除文档时,递减counts文档的count属性。
w.r.t价格(文档读取= 1)和快速数据检索上述解决方案是很好的。