LoginSignup
5
2

More than 3 years have passed since last update.

Cloud Firestore で特定の collection のドキュメント全件数を count する方法

Last updated at Posted at 2020-07-04

概要

Cloud Firestore で特定の collection のドキュメント全件数を count するサンプルコードをご紹介します。

前提知識: count() クエリは無い

まず、前提として Firestore には db.collection("users").count() みたいな count() クエリはありません。

結論: FieldValue.increment(1) を活用する

count() クエリが無いため、以下のように db.collection("users") のドキュメントが増減するタイミングで、ドキュメント全件数を管理する db.collection("counters") の値を FieldValue.increment() で増減させて、これでドキュメント全件数を管理します。

db.collection("counters").doc("user").update({ count: FieldValue.increment(1) })

サンプルコード: 特定 collection のドキュメント全件数 count

const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
const FieldValue = admin.firestore.FieldValue;

db.collection("users")
  .add({
    name: 'test'
  })
  .then(() => {
    return db
      .collection("counters")
      .doc("user")
      .update({ count: FieldValue.increment(1) })
      .finally(() => {
        return res.status(200).send("OK");
      });
  })
  .catch((err) => {
    console.error(err);
    return res.status(500).send("NG");
  });

以上、Cloud Firestore で特定の collection のドキュメント全件数を count したい、現場からお送りしました。

参考情報

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2