Constructor
new Firestore(settingsopt)
Parameters:
Name | Type | Attributes | Description | ||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
settings |
Object |
<optional> |
Properties
|
- Source:
- See:
Examples
<caption>Install the client library with <a
href="https://www.npmjs.com/">npm</a>:</caption> npm install --save
var Firestore = require('@google-cloud/firestore');
<caption>Create a client that uses <a
href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application
Default Credentials (ADC)</a>:</caption> var firestore = new Firestore();
<caption>Create a client with <a
href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit
credentials</a>:</caption> var firestore = new Firestore({ projectId:
'your-project-id', keyFilename: '/path/to/keyfile.json'
});
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.
let doc = await document.get();
console.log('Read the document');
// Delete the document.
await document.delete();
console.log('Deleted the document');
}
quickstart();
Methods
batch() → {WriteBatch}
Creates a WriteBatch, used for performing multiple writes as a single atomic operation.
Example
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(`Added document at ${res.writeResults[0].updateTime}`);
});
collection(collectionPath) → {CollectionReference}
Gets a CollectionReference instance that refers to the collection at the specified path.
Parameters:
Name | Type | Description |
---|---|---|
collectionPath |
string |
A slash-separated path to a collection. |
Example
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) → {Query}
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.
Parameters:
Name | Type | Description |
---|---|---|
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. |
Example
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) → {DocumentReference}
Gets a DocumentReference instance that refers to the document at the specified path.
Parameters:
Name | Type | Description |
---|---|---|
documentPath |
string |
A slash-separated path to a document. |
Example
let documentRef = firestore.doc('collection/document');
console.log(`Path of document is ${documentRef.path}`);
getAll(…documentRefsOrReadOptions) → {Promise.<Array.<DocumentSnapshot>>}
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.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
documentRefsOrReadOptions |
DocumentReference | ReadOptions |
<repeatable> |
The
|
Example
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() → {Promise.<Array.<CollectionReference>>}
Fetches the root collections that are associated with this Firestore database.
Example
firestore.listCollections().then(collections => {
for (let collection of collections) {
console.log(`Found collection with id: ${collection.id}`);
}
});
runTransaction(updateFunction, transactionOptionsopt) → {Promise}
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. Transactions are committed once 'updateFunction' resolves and attempted up to five times on failure.
Parameters:
Name | Type | Attributes | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
updateFunction |
function |
The function to execute within the transaction context. |
|||||||||
transactionOptions |
object |
<optional> |
Transaction options. Properties
|
Example
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)
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.
Parameters:
Name | Type | Description |
---|---|---|
settings |
object |
The settings to use for all Firestore operations. |
terminate()
Terminates the Firestore client and closes all open streams.
Type Definitions
logFunction(Log)
A logging function that takes a single string.
Parameters:
Name | Type | Description |
---|---|---|
Log |
string |
message |