Getting started with Firestore

Getting started with Firestore

Code sample

Kotlin

// Create the client.
val db = FirestoreOptions.newBuilder()
    .setTimestampsInSnapshotsEnabled(true)
    .build()
    .service

// Fetch the document reference and data object.
val docRef = db.collection(collectionName).document(documentName)
val data = docRef
        .get() // future
        .get() // snapshot
        .data ?: error("Document $collectionName:$documentName not found") // MutableMap

// Print the retrieved data.
data.forEach { key, value -> println("$key: $value") }

Node.js

const {Firestore} = require('@google-cloud/firestore');
const express = require('express');
const session = require('express-session');
const app = express();

const {FirestoreStore} = require('@google-cloud/connect-firestore');

app.use(
  session({
    store: new FirestoreStore({
      dataset: new Firestore(),
      kind: 'express-sessions',
    }),
    secret: 'my-secret',
    resave: false,
    saveUninitialized: true,
  })
);

app.get('/', (req, res) => {
  if (!req.session.views) {
    req.session.views = 0;
  }
  const views = req.session.views++;
  res.send(`Views ${views}`);
});

app.listen(4830, () => {
  console.log('Example app listening on port 4830!');
});

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.