Skip to content
This repository has been archived by the owner on May 17, 2022. It is now read-only.

K.3 Add Data

Hadi Tavakoli edited this page Jun 16, 2019 · 2 revisions

Add Data to Cloud Firestore

There are several ways to write data to Cloud Firestore:

  • Set the data of a document within a collection, explicitly specifying a document identifier.
  • Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier.
  • Create an empty document with an automatically generated identifier, and assign data to it later.

This guide explains how to use the write() and add() methods to write data to Cloud Firestore.

Write a document

To create or overwrite a single document, use the write() method:

var city:Object = {
	name: "Los Angeles",
	state: "CA",
	country: "USA"
};

var document:DocumentReference = Firestore.collection("cities").document("LA");
document.addEventListener(FirestoreEvents.DOCUMENT_SET_SUCCESS, onDocWriteSuccess);
document.addEventListener(FirestoreEvents.DOCUMENT_SET_FAILURE, onDocWriteFailure);
document.write(city);

function onDocWriteSuccess(e:FirestoreEvents):void
{
	var d:DocumentReference = e.target as DocumentReference;
	d.removeEventListener(FirestoreEvents.DOCUMENT_SET_SUCCESS, onDocWriteSuccess);
	d.removeEventListener(FirestoreEvents.DOCUMENT_SET_FAILURE, onDocWriteFailure);
	
	trace("Document successfully written!");
}

function onDocWriteFailure(e:FirestoreEvents):void
{
	var d:DocumentReference = e.target as DocumentReference;
	d.removeEventListener(FirestoreEvents.DOCUMENT_SET_SUCCESS, onDocWriteSuccess);
	d.removeEventListener(FirestoreEvents.DOCUMENT_SET_FAILURE, onDocWriteFailure);
	
	trace("Error writing document: " + e.msg);
}

If the document does not exist, it will be created. If the document does exist, its contents will be overwritten with the newly provided data, unless you specify that the data should be merged into the existing document, as follows:

var city:Object = {
	capital: true
};

var document:DocumentReference = Firestore.collection("cities").document("BJ");
document.addEventListener(FirestoreEvents.DOCUMENT_SET_SUCCESS, onDocWriteSuccess);
document.addEventListener(FirestoreEvents.DOCUMENT_SET_FAILURE, onDocWriteFailure);

var setOptions:SetOptions = new SetOptions();
setOptions.merge();

document.write(city, setOptions);

If you're not sure whether the document exists, pass the option to merge the new data with any existing document to avoid overwriting entire documents.

Data Types

Cloud Firestore lets you write a variety of data types inside a document, including strings, booleans, numbers, and nested arrays and objects.

var docData:Object = {
	stringExample: "Hello world!",
	booleanExample: true,
	numberExample: 3.14159265,
	serverTime:FieldValue.TIMESTAMP(),
	arrayExample:[
		"Hello world!",
		false,
		{key:"value"}
	],
	objectExample:{
		"key": "can host other objects or arrays..."
	}
};

var document:DocumentReference = Firestore.collection("data").document("one");
document.addEventListener(FirestoreEvents.DOCUMENT_SET_SUCCESS, onDocWriteSuccess);
document.addEventListener(FirestoreEvents.DOCUMENT_SET_FAILURE, onDocWriteFailure);
document.write(docData);

Add a document

When you use write() to create a document, you must specify an ID for the document to create. For example:

Firestore.collection("cities").document("new-city-id").write(data);

But sometimes there isn't a meaningful ID for the document, and it's more convenient to let Cloud Firestore auto-generate an ID for you. You can do this by calling add():

// Add a new document with a generated id.
var data:Object = {
	name: "Tokyo",
	country: "Japan"
};

var collection:CollectionReference = Firestore.collection("cities");
collection.addEventListener(FirestoreEvents.COLLECTION_ADD_SUCCESS, onCollectionAddSuccess);
collection.addEventListener(FirestoreEvents.COLLECTION_ADD_FAILURE, onCollectionAddFailure);
collection.add(data);

function onCollectionAddSuccess(e:FirestoreEvents):void
{
	var c:CollectionReference = e.target as CollectionReference;
	c.removeEventListener(FirestoreEvents.COLLECTION_ADD_SUCCESS, onCollectionAddSuccess);
	c.removeEventListener(FirestoreEvents.COLLECTION_ADD_FAILURE, onCollectionAddFailure);
	
	trace("DocumentSnapshot added with ID: " + e.documentReference.documentId);
}

function onCollectionAddFailure(e:FirestoreEvents):void
{
	var c:CollectionReference = e.target as CollectionReference;
	c.removeEventListener(FirestoreEvents.COLLECTION_ADD_SUCCESS, onCollectionAddSuccess);
	c.removeEventListener(FirestoreEvents.COLLECTION_ADD_FAILURE, onCollectionAddFailure);
	
	trace("Error adding document: " + e.msg);
}

Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.

In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call document():

var document:DocumentReference = Firestore.collection("data").document();
document.write(data);

Behind the scenes, .add(...) and . document().write(...) are completely equivalent, so you can use whichever is more convenient.

Update a document

To update some fields of a document without overwriting the entire document, use the update() method:

var washingtonRef:DocumentReference = Firestore.collection("cities").document("DC");
washingtonRef.addEventListener(FirestoreEvents.DOCUMENT_UPDATE_SUCCESS, onUpdateSuccess);
washingtonRef.addEventListener(FirestoreEvents.DOCUMENT_UPDATE_FAILURE, onUpdateFailure);
washingtonRef.update({capital: true});

Update fields in nested objects

If your document contains nested objects, you can use "dot notation" to reference nested fields within the document when you call update():

// Assume the document contains:
// {
//   name: "Frank",
//   favorites: { food: "Pizza", color: "Blue", subject: "recess" }
//   age: 12
// }
//
// To update age and favorite color:
var doc:DocumentReference = Firestore.collection("users").document("frank");

var updateObj:Object = {};
updateObj.age = 13;
updateObj["favorites.color"] = "Red";
				
doc.update(updateObj);

Introduction to Firebase ANEs collection for Adobe Air apps


Get Started with Firebase Core in AIR

  1. Prerequisites
  2. Add Firebase to your app
  3. Add the Firebase SDK
  4. Init Firebase Core
  5. Available ANEs
  6. Managing Firebase iid

Get Started with Analytics

  1. Add Analytics ANE
  2. Init Analytics ANE
  3. Log Events
  4. Set User Properties

Get Started with Crashlytics

  1. Add Crashlytics ANE
  2. Test Your Implementation
  3. Customize Crash Reports
  4. Upload .dSYM for iOS apps

Get Started with DynamicLinks

  1. Add DynamicLinks ANE
  2. Init DynamicLinks ANE
  3. Create DynamicLinks
  4. Receive DynamicLinks
  5. View Analytics

Get Started with Authentication

  1. Add Authentication
  2. Init Authentication
  3. Manage Users
  4. Phone Number
  5. Custom Auth
  6. Anonymous Auth
  7. State in Email Actions
  8. Email Link Authentication

Get Started with FCM + OneSignal

  1. Add FCM ANE
  2. Init FCM ANE
  3. Send Your 1st Message
  4. Send Msg to Topics
  5. Understanding FCM Messages
  6. init OneSignal

Get Started with Firestore

  1. Add Firestore
  2. Init Firestore
  3. Add Data
  4. Transactions & Batches
  5. Delete Data
  6. Manage the Console
  7. Get Data
  8. Get Realtime Updates
  9. Simple and Compound
  10. Order and Limit Data
  11. Paginate Data
  12. Manage Indexes
  13. Secure Data
  14. Offline Data
  15. Where to Go From Here

Get Started with Realtime Database

  1. Add Realtime Database
  2. Init Realtime Database
  3. Structure Your Database
  4. Save Data
  5. Retrieve Data
  6. Enable Offline Capabilities

Get Started with Remote Config

  1. Parameters and Conditions
  2. Add Remote Config
  3. Init Remote Config

Get Started with Performance

  1. Add Performance ANE
  2. Init & Start Monitoring

Get Started with Storage

  1. Add Storage ANE
  2. Init Storage ANE
  3. Upload Files to Storage
  4. Download Files to Air
  5. Use File Metadata
  6. Delete Files

Get Started with Functions

  1. Write & Deploy Functions
  2. Add Functions ANE
  3. Init Functions
Clone this wiki locally