toFirestoreRaw method

Map<String, dynamic> toFirestoreRaw({
  1. List<String>? fieldsToExclude,
})

Convert to Firestore with explicit control (advanced use).

Allows setting documents with specific timestamps without using FieldValue.serverTimestamp(). Useful for data migrations or when you need full control over all field values.

Parameters:

  • fieldsToExclude: List of field names to exclude from the output.

Example:

// Migration or batch import
await firestore.collection('posts')
  .doc(postId)
  .set(post.toFirestoreRaw());

Implementation

Map<String, dynamic> toFirestoreRaw({
  List<String>? fieldsToExclude,
}) {
  final json = toJson();
  final processed = Map<String, dynamic>.from(json);

  // Remove null values and excluded fields
  processed.removeWhere((key, value) => value == null);
  if (fieldsToExclude != null) {
    for (final field in fieldsToExclude) {
      processed.remove(field);
    }
  }

  // Convert DateTime to Timestamp but don't use FieldValue
  processed.forEach((key, value) {
    if (value is DateTime) {
      processed[key] = Timestamp.fromDate(value);
    }
  });

  return processed;
}