CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-native-firebase--firestore

React Native Firebase Cloud Firestore provides a NoSQL document database with real-time synchronization capabilities.

Pending
Overview
Eval results
Files

data-types.mddocs/

Data Types & Field Values

Rich data model supporting various data types including custom Firestore types and special field operations.

Capabilities

Timestamp Operations

Represent precise timestamps with nanosecond accuracy, supporting server timestamps and date conversions.

class Timestamp {
  /**
   * Current server timestamp
   * @returns Timestamp representing current server time
   */
  static now(): FirebaseFirestoreTypes.Timestamp;

  /**
   * Create timestamp from JavaScript Date
   * @param date - Date object to convert
   * @returns Timestamp representation of the date
   */
  static fromDate(date: Date): FirebaseFirestoreTypes.Timestamp;

  /**
   * Create timestamp from milliseconds since epoch
   * @param milliseconds - Milliseconds since Unix epoch
   * @returns Timestamp representation
   */
  static fromMillis(milliseconds: number): FirebaseFirestoreTypes.Timestamp;

  /**
   * Seconds component of the timestamp
   */
  readonly seconds: number;

  /**
   * Nanoseconds component of the timestamp
   */
  readonly nanoseconds: number;

  /**
   * Create a timestamp with specific seconds and nanoseconds
   * @param seconds - Seconds since Unix epoch
   * @param nanoseconds - Nanosecond component (0-999,999,999)
   */
  constructor(seconds: number, nanoseconds: number);

  /**
   * Convert to JavaScript Date object
   * @returns Date representation (may lose nanosecond precision)
   */
  toDate(): Date;

  /**
   * Convert to milliseconds since epoch
   * @returns Milliseconds representation
   */
  toMillis(): number;

  /**
   * String representation of the timestamp
   * @returns ISO 8601 string representation
   */
  toString(): string;

  /**
   * JSON representation for serialization
   * @returns Object with seconds and nanoseconds properties
   */
  toJSON(): { seconds: number; nanoseconds: number };

  /**
   * Primitive value for comparison
   * @returns String representation for comparison
   */
  valueOf(): string;

  /**
   * Check if two timestamps are equal
   * @param other - Other timestamp to compare
   * @returns True if timestamps are equal
   */
  isEqual(other: FirebaseFirestoreTypes.Timestamp): boolean;
}

Usage Examples:

import firestore from '@react-native-firebase/firestore';

// Create timestamps
const now = firestore.Timestamp.now();
const specificTime = firestore.Timestamp.fromDate(new Date('2023-01-01'));
const fromMillis = firestore.Timestamp.fromMillis(Date.now());
const precise = new firestore.Timestamp(1672531200, 123456789); // 2023-01-01 with nanoseconds

// Use in document operations
await firestore().collection('events').add({
  name: 'New Year Celebration',
  startTime: firestore.Timestamp.fromDate(new Date('2023-01-01T00:00:00Z')),
  endTime: firestore.Timestamp.fromDate(new Date('2023-01-01T02:00:00Z')),
  registeredAt: firestore.Timestamp.now()
});

// Convert timestamps
const eventDoc = await firestore().collection('events').doc('eventId').get();
const eventData = eventDoc.data();

if (eventData) {
  const startTime = eventData.startTime as firestore.Timestamp;
  const startDate = startTime.toDate();
  const startMillis = startTime.toMillis();
  
  console.log('Event starts at:', startDate.toISOString());
  console.log('Timestamp seconds:', startTime.seconds);
  console.log('Timestamp nanoseconds:', startTime.nanoseconds);
}

GeoPoint Operations

Represent geographic coordinates with latitude and longitude values.

class GeoPoint {
  /**
   * Latitude coordinate (-90 to 90)
   */
  readonly latitude: number;

  /**
   * Longitude coordinate (-180 to 180)
   */
  readonly longitude: number;

  /**
   * Create a geographic point
   * @param latitude - Latitude coordinate (-90 to 90)
   * @param longitude - Longitude coordinate (-180 to 180)
   */
  constructor(latitude: number, longitude: number);

  /**
   * Check if two geo points are equal
   * @param other - Other GeoPoint to compare
   * @returns True if coordinates are equal
   */
  isEqual(other: FirebaseFirestoreTypes.GeoPoint): boolean;

  /**
   * JSON representation for serialization
   * @returns Object with latitude and longitude properties
   */
  toJSON(): { latitude: number; longitude: number };
}

Usage Examples:

import firestore from '@react-native-firebase/firestore';

// Create GeoPoints
const newYork = new firestore.GeoPoint(40.7128, -74.0060);
const london = new firestore.GeoPoint(51.5074, -0.1278);

// Store locations in documents
await firestore().collection('locations').add({
  name: 'Central Park',
  coordinates: new firestore.GeoPoint(40.7829, -73.9654),
  city: 'New York',
  country: 'USA'
});

// Query by proximity (requires composite index)
const nearbyLocations = await firestore()
  .collection('locations')
  .where('coordinates', '>=', new firestore.GeoPoint(40.7, -74.1))
  .where('coordinates', '<=', new firestore.GeoPoint(40.8, -73.9))
  .get();

// Work with retrieved GeoPoints
const locationDoc = await firestore().collection('locations').doc('locationId').get();
const locationData = locationDoc.data();

if (locationData) {
  const coordinates = locationData.coordinates as firestore.GeoPoint;
  
  console.log('Latitude:', coordinates.latitude);
  console.log('Longitude:', coordinates.longitude);
  console.log('Coordinates JSON:', coordinates.toJSON());
  
  // Check if coordinates match
  const isNearCentralPark = coordinates.isEqual(new firestore.GeoPoint(40.7829, -73.9654));
}

Field Value Operations

Special values for atomic field operations like server timestamps, increments, and array modifications.

class FieldValue {
  /**
   * Server timestamp placeholder
   * @returns FieldValue representing server timestamp
   */
  static serverTimestamp(): FirebaseFirestoreTypes.FieldValue;

  /**
   * Field deletion marker
   * @returns FieldValue that deletes the field
   */
  static delete(): FirebaseFirestoreTypes.FieldValue;

  /**
   * Numeric increment operation
   * @param n - Number to increment by (can be negative for decrement)
   * @returns FieldValue that increments the field
   */
  static increment(n: number): FirebaseFirestoreTypes.FieldValue;

  /**
   * Array union operation (adds elements not already present)
   * @param elements - Elements to add to the array
   * @returns FieldValue that performs array union
   */
  static arrayUnion(...elements: any[]): FirebaseFirestoreTypes.FieldValue;

  /**
   * Array remove operation (removes all instances of elements)
   * @param elements - Elements to remove from the array
   * @returns FieldValue that performs array removal
   */
  static arrayRemove(...elements: any[]): FirebaseFirestoreTypes.FieldValue;

  /**
   * Check if two field values are equal
   * @param other - Other FieldValue to compare
   * @returns True if field values are equal
   */
  isEqual(other: FirebaseFirestoreTypes.FieldValue): boolean;
}

Usage Examples:

import firestore from '@react-native-firebase/firestore';

// Server timestamps
await firestore().collection('posts').add({
  title: 'Hello World',
  content: 'This is my first post',
  createdAt: firestore.FieldValue.serverTimestamp(),
  updatedAt: firestore.FieldValue.serverTimestamp()
});

// Increment/decrement operations
await firestore().collection('counters').doc('pageViews').update({
  count: firestore.FieldValue.increment(1)
});

await firestore().collection('users').doc('userId').update({
  credits: firestore.FieldValue.increment(-10), // Deduct 10 credits
  lastPurchaseAt: firestore.FieldValue.serverTimestamp()
});

// Array operations
await firestore().collection('users').doc('userId').update({
  // Add tags (only if not already present)
  tags: firestore.FieldValue.arrayUnion('premium', 'verified'),
  
  // Remove tags (all instances)
  blockedUsers: firestore.FieldValue.arrayRemove('spam-user-1', 'spam-user-2')
});

// Delete fields
await firestore().collection('users').doc('userId').update({
  temporaryField: firestore.FieldValue.delete(),
  updatedAt: firestore.FieldValue.serverTimestamp()
});

// Complex document update with multiple field values
await firestore().collection('products').doc('productId').update({
  // Increment view count
  viewCount: firestore.FieldValue.increment(1),
  
  // Add to categories
  categories: firestore.FieldValue.arrayUnion('featured'),
  
  // Update timestamp
  lastViewedAt: firestore.FieldValue.serverTimestamp(),
  
  // Remove deprecated field
  oldField: firestore.FieldValue.delete()
});

Blob Operations

Handle binary data with base64 and Uint8Array conversions.

class Blob {
  /**
   * Create blob from base64 string
   * @param base64 - Base64 encoded string
   * @returns Blob containing the decoded data
   */
  static fromBase64String(base64: string): FirebaseFirestoreTypes.Blob;

  /**
   * Create blob from byte array
   * @param array - Uint8Array containing raw bytes
   * @returns Blob containing the byte data
   */
  static fromUint8Array(array: Uint8Array): FirebaseFirestoreTypes.Blob;

  /**
   * Convert blob to base64 string
   * @returns Base64 encoded representation
   */
  toBase64(): string;

  /**
   * Convert blob to byte array
   * @returns Uint8Array containing the raw bytes
   */
  toUint8Array(): Uint8Array;

  /**
   * Check if two blobs are equal
   * @param other - Other Blob to compare
   * @returns True if blobs contain the same data
   */
  isEqual(other: FirebaseFirestoreTypes.Blob): boolean;
}

Usage Examples:

import firestore from '@react-native-firebase/firestore';

// Create blobs from different sources
const base64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==';
const blobFromBase64 = firestore.Blob.fromBase64String(base64Data);

const byteArray = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const blobFromBytes = firestore.Blob.fromUint8Array(byteArray);

// Store binary data in documents
await firestore().collection('files').add({
  name: 'small-image.png',
  mimeType: 'image/png',
  size: 68,
  data: blobFromBase64,
  uploadedAt: firestore.FieldValue.serverTimestamp()
});

// Retrieve and work with blob data
const fileDoc = await firestore().collection('files').doc('fileId').get();
const fileData = fileDoc.data();

if (fileData) {
  const blobData = fileData.data as firestore.Blob;
  
  // Convert back to different formats
  const base64String = blobData.toBase64();
  const uint8Array = blobData.toUint8Array();
  
  console.log('Base64:', base64String);
  console.log('Byte array length:', uint8Array.length);
  console.log('First byte:', uint8Array[0]);
}

// Compare blobs
const blob1 = firestore.Blob.fromBase64String('SGVsbG8='); // "Hello"
const blob2 = firestore.Blob.fromBase64String('SGVsbG8='); // "Hello"
const blob3 = firestore.Blob.fromBase64String('V29ybGQ='); // "World"

console.log('blob1 equals blob2:', blob1.isEqual(blob2)); // true
console.log('blob1 equals blob3:', blob1.isEqual(blob3)); // false

Field Path Operations

Reference document fields, including nested fields and special field names.

class FieldPath {
  /**
   * Special field path for document ID
   * @returns FieldPath referencing the document ID
   */
  static documentId(): FirebaseFirestoreTypes.FieldPath;

  /**
   * Create a field path from field names
   * @param fieldNames - Sequence of field names for nested access
   */
  constructor(...fieldNames: string[]);

  /**
   * Check if two field paths are equal
   * @param other - Other FieldPath to compare
   * @returns True if field paths are equal
   */
  isEqual(other: FirebaseFirestoreTypes.FieldPath): boolean;
}

Usage Examples:

import firestore from '@react-native-firebase/firestore';

// Create field paths for nested fields
const profileNamePath = new firestore.FieldPath('profile', 'displayName');
const settingsThemePath = new firestore.FieldPath('settings', 'ui', 'theme');

// Use in queries
const usersWithDisplayName = await firestore()
  .collection('users')
  .where(profileNamePath, '!=', null)
  .get();

// Use in updates
await firestore().collection('users').doc('userId').update({
  [profileNamePath]: 'John Doe',
  [settingsThemePath]: 'dark'
});

// Alternative syntax for updates
await firestore().collection('users').doc('userId').update(
  profileNamePath, 'Jane Doe',
  settingsThemePath, 'light'
);

// Document ID field path (useful for queries)
const documentIdPath = firestore.FieldPath.documentId();

// Query using document ID
const specificUsers = await firestore()
  .collection('users')
  .where(documentIdPath, 'in', ['user1', 'user2', 'user3'])
  .get();

// Order by document ID
const orderedByIdQuery = await firestore()
  .collection('users')
  .orderBy(documentIdPath)
  .get();

// Complex nested field operations
const addressPath = new firestore.FieldPath('contact', 'address', 'street');
const phonePath = new firestore.FieldPath('contact', 'phone', 'primary');

await firestore().collection('users').doc('userId').update({
  [addressPath]: '123 Main St',
  [phonePath]: '+1-555-0123',
  updatedAt: firestore.FieldValue.serverTimestamp()
});

Type Validation and Conversion

/**
 * Check if a value is a Firestore Timestamp
 */
function isTimestamp(value: any): value is FirebaseFirestoreTypes.Timestamp;

/**
 * Check if a value is a Firestore GeoPoint
 */
function isGeoPoint(value: any): value is FirebaseFirestoreTypes.GeoPoint;

/**
 * Check if a value is a Firestore FieldValue
 */
function isFieldValue(value: any): value is FirebaseFirestoreTypes.FieldValue;

/**
 * Check if a value is a Firestore Blob
 */
function isBlob(value: any): value is FirebaseFirestoreTypes.Blob;

/**
 * Check if a value is a Firestore FieldPath
 */
function isFieldPath(value: any): value is FirebaseFirestoreTypes.FieldPath;

Usage Examples:

import firestore from '@react-native-firebase/firestore';

// Type checking utility functions
function processDocumentData(data: any) {
  Object.entries(data).forEach(([key, value]) => {
    if (firestore.Timestamp.prototype.isPrototypeOf(value)) {
      console.log(`${key} is a Timestamp:`, value.toDate());
    } else if (firestore.GeoPoint.prototype.isPrototypeOf(value)) {
      console.log(`${key} is a GeoPoint:`, value.latitude, value.longitude);
    } else if (firestore.Blob.prototype.isPrototypeOf(value)) {
      console.log(`${key} is a Blob with ${value.toUint8Array().length} bytes`);
    } else {
      console.log(`${key} is a regular value:`, value);
    }
  });
}

// Convert data for serialization
function serializeFirestoreData(data: any): any {
  if (data === null || data === undefined) {
    return data;
  }
  
  if (firestore.Timestamp.prototype.isPrototypeOf(data)) {
    return { _type: 'timestamp', value: data.toMillis() };
  }
  
  if (firestore.GeoPoint.prototype.isPrototypeOf(data)) {
    return { _type: 'geopoint', value: data.toJSON() };
  }
  
  if (firestore.Blob.prototype.isPrototypeOf(data)) {
    return { _type: 'blob', value: data.toBase64() };
  }
  
  if (Array.isArray(data)) {
    return data.map(serializeFirestoreData);
  }
  
  if (typeof data === 'object') {
    const serialized: any = {};
    Object.entries(data).forEach(([key, value]) => {
      serialized[key] = serializeFirestoreData(value);
    });
    return serialized;
  }
  
  return data;
}

Types

/**
 * Supported Firestore data types
 */
type DocumentFieldType = 
  | string 
  | number 
  | boolean 
  | { [key: string]: DocumentFieldType } 
  | DocumentFieldType[] 
  | null 
  | FirebaseFirestoreTypes.Timestamp 
  | FirebaseFirestoreTypes.GeoPoint 
  | FirebaseFirestoreTypes.Blob 
  | FirebaseFirestoreTypes.FieldPath 
  | FirebaseFirestoreTypes.FieldValue 
  | FirebaseFirestoreTypes.DocumentReference 
  | FirebaseFirestoreTypes.CollectionReference;

/**
 * Document data structure
 */
interface DocumentData {
  [field: string]: DocumentFieldType;
}

/**
 * Snapshot options for data retrieval
 */
interface SnapshotOptions {
  /**
   * How to handle server timestamps that haven't been set yet
   * - 'estimate': Use local estimate of server time
   * - 'previous': Use previous field value  
   * - 'none': Return null for unresolved server timestamps
   */
  serverTimestamps?: 'estimate' | 'previous' | 'none';
}

Install with Tessl CLI

npx tessl i tessl/npm-react-native-firebase--firestore

docs

data-types.md

database-operations.md

index.md

modular-api.md

offline-network.md

querying-filtering.md

realtime-sync.md

transactions-batches.md

tile.json