The Firestore client represents a Firestore Database and is the entry point for all Firestore operations.
Package
@google-cloud/firestoreExamples
Install the client library with npm :
npm
install
--
save
@
google
-
cloud
/
firestore
Import the client library
var
Firestore
=
require
(
' @google-cloud/firestore
'
);
Create a client that uses Application Default Credentials (ADC) :
var
firestore
=
new
Firestore
();
Create a client with explicit credentials :
var
firestore
=
new
Firestore
({
projectId
:
'your-project-id'
,
keyFilename
:
'/path/to/keyfile.json'
});
Full quickstart example:
const
{
Firestore
}
=
require
(
' @google-cloud/firestore
'
);
// Create a new client
const
firestore
=
new
Firestore
();
async
function
quickstart
()
{
// Obtain a document reference.
const
document
=
firestore
.
doc
(
'posts/intro-to-firestore'
);
// Enter new data into the document.
await
document
.
set
({
title
:
'Welcome to Firestore'
,
body
:
'Hello World'
,
});
console
.
log
(
'Entered new data into the document'
);
// Update an existing document.
await
document
.
update
({
body
:
'My first Firestore app'
,
});
console
.
log
(
'Updated an existing document'
);
// Read the document.
const
doc
=
await
document
.
get
();
console
.
log
(
'Read the document'
);
// Delete the document.
await
document
.
delete
();
console
.
log
(
'Deleted the document'
);
}
quickstart
();
Constructors
(constructor)(settings)
constructor
(
settings
?:
firestore
.
Settings
);
Constructs a new instance of the Firestore
class
settings
firestore.Settings
[Configuration object](#/docs).
Methods
batch()
batch
()
:
WriteBatch
;
Creates a [WriteBatch] WriteBatch , used for performing multiple writes as a single atomic operation.
{WriteBatch} A WriteBatch that operates on this Firestore client.
let
writeBatch
=
firestore
.
batch
();
// Add two documents in an atomic batch.
let
data
=
{
foo
:
'bar'
};
writeBatch
.
set
(
firestore
.
doc
(
'col/doc1'
),
data
);
writeBatch
.
set
(
firestore
.
doc
(
'col/doc2'
),
data
);
writeBatch
.
commit
().
then
(
res
=
>
{
console
.
log
(
'Successfully executed batch.'
);
});
bulkWriter(options)
bulkWriter
(
options
?:
firestore
.
BulkWriterOptions
)
:
BulkWriter
;
Creates a [BulkWriter] BulkWriter , used for performing multiple writes in parallel. Gradually ramps up writes as specified by the 500/50/5 rule.
If you pass [BulkWriterOptions], you can configure the throttling rates for the created BulkWriter.
options
firestore.BulkWriterOptions
BulkWriter options.
{BulkWriter} A BulkWriter that operates on this Firestore client.
let
bulkWriter
=
firestore
.
bulkWriter
();
bulkWriter
.
create
(
firestore
.
doc
(
'col/doc1'
),
{
foo
:
'bar'
})
.
then
(
res
=
>
{
console
.
log
(
`Added document at
${
res
.
writeTime
}
`
);
});
bulkWriter
.
update
(
firestore
.
doc
(
'col/doc2'
),
{
foo
:
'bar'
})
.
then
(
res
=
>
{
console
.
log
(
`Updated document at
${
res
.
writeTime
}
`
);
});
bulkWriter
.
delete
(
firestore
.
doc
(
'col/doc3'
))
.
then
(
res
=
>
{
console
.
log
(
`Deleted document at
${
res
.
writeTime
}
`
);
});
await
bulkWriter
.
close
().
then
(()
=
>
{
console
.
log
(
'Executed all writes'
);
});
bundle(name)
bundle
(
name
?:
string
)
:
BundleBuilder
;
Creates a new BundleBuilder
instance to package selected Firestore data into a bundle.
name
string
BundleBuilder
collection(collectionPath)
collection
(
collectionPath
:
string
)
:
CollectionReference
;
Gets a [CollectionReference] CollectionReference instance that refers to the collection at the specified path.
collectionPath
string
A slash-separated path to a collection.
{CollectionReference} The [CollectionReference] CollectionReference instance.
let
collectionRef
=
firestore
.
collection
(
'collection'
);
// Add a document with an auto-generated ID.
collectionRef
.
add
({
foo
:
'bar'
}).
then
((
documentRef
)
=
>
{
console
.
log
(
`Added document at
${
documentRef
.
path
}
)`
);
});
collectionGroup(collectionId)
collectionGroup
(
collectionId
:
string
)
:
CollectionGroup
;
Creates and returns a new Query that includes all documents in the database that are contained in a collection or subcollection with the given collectionId.
collectionId
string
Identifies the collections to query over. Every collection or subcollection with this ID as the last segment of its path will be included. Cannot contain a slash.
let
docA
=
firestore
.
doc
(
'mygroup/docA'
).
set
({
foo
:
'bar'
});
let
docB
=
firestore
.
doc
(
'abc/def/mygroup/docB'
).
set
({
foo
:
'bar'
});
Promise
.
all
([
docA
,
docB
]).
then
(()
=
>
{
let
query
=
firestore
.
collectionGroup
(
'mygroup'
);
query
=
query
.
where
(
'foo'
,
'=='
,
'bar'
);
return
query
.
get
().
then
(
snapshot
=
>
{
console
.
log
(
`Found
${
snapshot
.
size
}
documents.`
);
});
});
doc(documentPath)
doc
(
documentPath
:
string
)
:
DocumentReference
;
Gets a [DocumentReference] DocumentReference instance that refers to the document at the specified path.
documentPath
string
A slash-separated path to a document.
let
documentRef
=
firestore
.
doc
(
'collection/document'
);
console
.
log
(
`Path of document is
${
documentRef
.
path
}
`
);
getAll(documentRefsOrReadOptions)
getAll<AppModelType
,
DbModelType
extends
firestore
.
DocumentData
> (...
documentRefsOrReadOptions
:
Array<firestore
.
DocumentReference<AppModelType
,
DbModelType
>
|
firestore
.
ReadOptions
> )
:
Promise<Array<DocumentSnapshot<AppModelType
,
DbModelType
>>> ;
Retrieves multiple documents from Firestore.
The first argument is required and must be of type DocumentReference
followed by any additional DocumentReference
documents. If used, the optional ReadOptions
must be the last argument.
documentRefsOrReadOptions
Array
< FirebaseFirestore.DocumentReference
<AppModelType, DbModelType> | FirebaseFirestore.ReadOptions
>
The DocumentReferences
to receive, followed by an optional field mask.
Promise
< Array
< DocumentSnapshot
<AppModelType, DbModelType>>>
{Promise<Array.
AppModelType
DbModelType
let
docRef1
=
firestore
.
doc
(
'col/doc1'
);
let
docRef2
=
firestore
.
doc
(
'col/doc2'
);
firestore
.
getAll
(
docRef1
,
docRef2
,
{
fieldMask
:
[
'user'
]
}).
then
(
docs
=
>
{
console
.
log
(
`First document:
${
JSON
.
stringify
(
docs
[
0
])
}
`
);
console
.
log
(
`Second document:
${
JSON
.
stringify
(
docs
[
1
])
}
`
);
});
listCollections()
listCollections
()
:
Promise<CollectionReference
[]>;
Fetches the root collections that are associated with this Firestore database.
firestore
.
listCollections
().
then
(
collections
=
>
{
for
(
let
collection
of
collections
)
{
console
.
log
(
`Found collection with id:
${
collection
.
id
}
`
);
}
});
recursiveDelete(ref, bulkWriter)
recursiveDelete
(
ref
:
firestore
.
CollectionReference<any
,
any
>
|
firestore
.
DocumentReference<any
,
any
> ,
bulkWriter
?:
BulkWriter
)
:
Promise<void>
;
Recursively deletes all documents and subcollections at and under the specified level.
If any delete fails, the promise is rejected with an error message containing the number of failed deletes and the stack trace of the last failed delete. The provided reference is deleted regardless of whether all deletes succeeded.
recursiveDelete()
uses a BulkWriter instance with default settings to perform the deletes. To customize throttling rates or add success/error callbacks, pass in a custom BulkWriter instance.
ref
FirebaseFirestore.CollectionReference
<any, any> | FirebaseFirestore.DocumentReference
<any, any>
The reference of a document or collection to delete.
bulkWriter
BulkWriter
A custom BulkWriter instance used to perform the deletes. A promise that resolves when all deletes have been performed. The promise is rejected if any of the deletes fail.
Promise
<void>
// Recursively delete a reference and log the references of failures.
const
bulkWriter
=
firestore
.
bulkWriter
();
bulkWriter
.
onWriteError
((
error
)
=
>
{
if
(
error
.
failedAttempts
<
max_retry_attempts
=
""
)
=
""
{
=
""
return
=
""
true
;
=
""
}
=
""
else
=
""
{
=
""
console
.
log
(
'failed="" write="" at="" document:="" '
,
=
""
error
.
documentref
.
path
);
=
""
return
=
""
false
;
=
""
}
=
""
});
=
""
await
=
""
firestore
.
recursivedelete
(
docref
,
=
""
bulkwriter
);
=
""
>
runTransaction(updateFunction, transactionOptions)
runTransaction<T>
(
updateFunction
:
(
transaction
:
Transaction
)
=
>
Promise<T>
,
transactionOptions
?:
firestore
.
ReadWriteTransactionOptions
|
firestore
.
ReadOnlyTransactionOptions
)
:
Promise<T>
;
Executes the given updateFunction and commits the changes applied within the transaction.
You can use the transaction object passed to 'updateFunction' to read and modify Firestore documents under lock. You have to perform all reads before before you perform any write.
Transactions can be performed as read-only or read-write transactions. By default, transactions are executed in read-write mode.
A read-write transaction obtains a pessimistic lock on all documents that are read during the transaction. These locks block other transactions, batched writes, and other non-transactional writes from changing that document. Any writes in a read-write transactions are committed once 'updateFunction' resolves, which also releases all locks.
If a read-write transaction fails with contention, the transaction is retried up to five times. The updateFunction
is invoked once for each attempt.
Read-only transactions do not lock documents. They can be used to read documents at a consistent snapshot in time, which may be up to 60 seconds in the past. Read-only transactions are not retried.
Transactions time out after 60 seconds if no documents are read. Transactions that are not committed within than 270 seconds are also aborted. Any remaining locks are released when a transaction times out.
T
updateFunction
(transaction: Transaction
) => Promise
<T>
The user function to execute within the transaction context.
transactionOptions
FirebaseFirestore.ReadWriteTransactionOptions
| FirebaseFirestore.ReadOnlyTransactionOptions
Transaction options.
Promise
<T>
{Promise
T
let
counterTransaction
=
firestore
.
runTransaction
(
transaction
=
>
{
let
documentRef
=
firestore
.
doc
(
'col/doc'
);
return
transaction
.
get
(
documentRef
).
then
(
doc
=
>
{
if
(
doc
.
exists
)
{
let
count
=
doc
.
get
(
'count'
)
||
0
;
if
(
count
>
10
)
{
return
Promise
.
reject
(
'Reached maximum count'
);
}
transaction
.
update
(
documentRef
,
{
count
:
++
count
});
return
Promise
.
resolve
(
count
);
}
transaction
.
create
(
documentRef
,
{
count
:
1
});
return
Promise
.
resolve
(
1
);
});
});
counterTransaction
.
then
(
res
=
>
{
console
.
log
(
`Count updated to
${
res
}
`
);
});
settings(settings)
settings
(
settings
:
firestore
.
Settings
)
:
void
;
Specifies custom settings to be used to configure the Firestore
instance. Can only be invoked once and before any other Firestore method.
If settings are provided via both settings()
and the Firestore
constructor, both settings objects are merged and any settings provided via settings()
take precedence.
settings
firestore.Settings
The settings to use for all Firestore operations.
void
snapshot_(documentName, readTime, encoding)
snapshot_
(
documentName
:
string
,
readTime
?:
google
.
protobuf
.
ITimestamp
,
encoding
?:
'protobufJS'
)
:
DocumentSnapshot
;
Creates a [DocumentSnapshot] DocumentSnapshot
or a [QueryDocumentSnapshot] QueryDocumentSnapshot
from a firestore.v1.Document
proto (or from a resource name for missing documents).
This API is used by Google Cloud Functions and can be called with both 'Proto3 JSON' and 'Protobuf JS' encoded data.
documentName
string
readTime
google.protobuf.ITimestamp
A 'Timestamp' proto indicating the time this document was read.
encoding
'protobufJS'
One of 'json' or 'protobufJS'. Applies to both the 'document' Proto and 'readTime'. Defaults to 'protobufJS'.
A QueryDocumentSnapshot for existing documents, otherwise a DocumentSnapshot.
snapshot_(documentName, readTime, encoding)
snapshot_
(
documentName
:
string
,
readTime
:
string
,
encoding
:
'json'
)
:
DocumentSnapshot
;
documentName
string
readTime
string
encoding
'json'
snapshot_(document, readTime, encoding)
snapshot_
(
document
:
api
.
IDocument
,
readTime
:
google
.
protobuf
.
ITimestamp
,
encoding
?:
'protobufJS'
)
:
QueryDocumentSnapshot
;
document
api.IDocument
readTime
google.protobuf.ITimestamp
encoding
'protobufJS'
snapshot_(document, readTime, encoding)
snapshot_
(
document
:
{
[
k
:
string
]
:
unknown
;
},
readTime
:
string
,
encoding
:
'json'
)
:
QueryDocumentSnapshot
;
document
{
[k: string]: unknown;
}
readTime
string
encoding
'json'
terminate()
terminate
()
:
Promise<void>
;
Terminates the Firestore client and closes all open streams.
A Promise that resolves when the client is terminated.
Promise
<void>
toJSON()
toJSON
()
:
object
;
Returns the Project ID to serve as the JSON representation of this Firestore instance.
An object that contains the project ID (or undefined
if not yet available).
object