I need the equivalent firebase realtime database query from the firestore query below
await db.collection('Events')
.where('EventName', '>=', 'startcode')
.where('EventName', '<', 'endcode').get()
.then((snapshot) => {
snapshot.forEach(doc => {
const data = doc.data()
searchList.push(data)
})
})
You can try filtering:
const snapshot = await firebase
.database()
.ref("/ref/to/events")
.orderBy("EventName")
.startAt("start_code")
.endBefore("end_code")
.once("value")
console.log(snapshot.val())
startAt() Return items greater than or equal to the specified key or
value, depending on the order-by method chosen.
endAt() Return items
less than or equal to the specified key or value, depending on the
order-by method chosen.
To use this query your db structure should look something like:
{
events: {
event1: {
EventName: "event1name"
},
event2: {
EventName: "event2name"
}
}
}
Related
My problem is that I use wrong query to get the date.
const SaveDateBase = async ( e) => {
e.preventDefault()
await setDoc(doc(db, "Users", "Pompy", "Pompy", user.uid), {
displayName: user.displayName,
uid: user?.uid,
modulyPV}).then(()=>{
console.log("moduly", modulyPV)
})
};
useEffect(() => {
const getUsers = async (users) => {
const URC = query(collection(db, "Users").document("Pompy").collection("Pompy"), where("uid", "==", user?.uid));
const data = await getDocs(URC)
setModulyPV(data.docs.map((doc) => ({...doc.data(), id: doc.id})))
}
getUsers();
},[])
The date are saved in date base, and I can successfully update/delete them, but I do something wrong to fetch (read?) them.
I guess is problem with the code.
You can get the data in diff ways, first "Pompy" seems to be your document where you are storing a nested collection then you document "Pompy" So for retrieve that specific document should be something like:
let snapshot = await db
.collection('Users')
.doc('Pompy')
.collection('Pompy')
.get()
snapshot.forEach(doc =>{
console.log('data:', doc.data())
})
Then to query into the nested collection would be something like querying the nested collections.
https://cloud.google.com/firestore/docs/samples/firestore-data-get-sub-collections?hl=es-419#firestore_data_get_sub_collections-nodejs
You can also use collection groups.
https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query
const pompys = query(collectionGroup(db, 'Pompy'), where("uid", "==", user?.uid));
i have a collection that is called employees, which includes documents and each document contains some data, and an array of objects that is called orgsanizations, for instance:
orgsanizations: [
{
orgId: 'org1',
registrationDate: '08/05/2021',
status: 'pending'
},
{
orgId: 'org2,
registrationDate: '12/01/2021',
status: 'approved'
}
];
I am trying to retrieve all the documents in employees that contains orgId === org1 in the orgsanizations, here is what i tried to do but keeps returning empty array.
const allEmployees = async () => {
const employeesList = db.collection('employees');
const snapshot = await employeesList
.where('orgsanizations', 'array-contains', { orgId: 'org1' })
.get();
if (snapshot.empty) {
console.log(snapshot.empty);
} else {
snapshot.forEach((doc) => {
console.log(doc.data());
});
}
};
};
Is there a solution for this or should start considering changing the structure to something else?
Thanks in advance
You can't check for the contents of a map, using array-contains. There are a couple of solutions for this...
Create a second array called orgIds, which contains only the orgId strings. You can then find any documents which contain these orgIds. To achieve this, you will need to write the orgId into the map AND the orgIds array.
Create an organizations sub-collection of your employee document and use a collectionGroup query.
{
organizations: [
{orgId: 'org1', registrationDate: '08/05/2021', status: 'pending'},
{orgId: 'org2', registrationDate: '12/01/2021', status: 'approved'}
],
orgIds: ['org1', 'org2']
}
const employeesList = db.collection('employees');
const snapshot = await employeesList
.where('orgIds', 'array-contains', 'org1')
.get();
You may also want to change your registrationDate to either a Timestamp or an ISO8601 string, so that you can sort them (if needed).
I have create document like this in react native, I am using rnfirebase library
firestore()
.collection('WaterCanData')
.doc(EntryDate)
.collection('Entries')
.doc(values.customerName)
.set({
CustomerName: values.customerName,
CansOut: values.cansOut,
JarsOut: values.jarsOut,
EmptyCansIn: values.emptyCansIn,
JarsIn: values.jarsIn,
Bottles: values.bottles,
Ice: values.ice
})
.then(() => {
console.log('Entry added!!!!!!!!!');
})
When I try to retrieve EntryDate from WaterCanData Coellection I am not able to fetch it(Document name appears in italic font), So how should I retrive this document which contains a subcollection, Below I have attached my ss of data structure
Data structure
Data structuree
The reason your document appears in italics is because it doesn't currently exist. In Cloud Firestore, subcollections can exist without requiring their parent document to also exist.
Non-existant documents will not appear in queries or snapshots in the client SDKs as stated in the Firebase Console.
This document does not exist, it will not appear in queries or snapshots
If you want to be able to get your entry dates, you need to create the document (which can be empty).
firebase.firestore()
.collection('WaterCanData')
.doc(EntryDate)
.set({}); // an empty document
To create the document at the same time as an entry on it's subcollection, you can use a batched write like so:
const db = firebase.firestore();
const batch = db.batch();
// get references to the relevant locations
const entryDateRef = db
.collection('WaterCanData')
.doc(EntryDate);
const customerRef = entryDateRef
.collection('Entries')
.doc(values.customerName);
// queue the data to write
batch.set(entryDateRef, {});
batch.set(customerRef, {
CustomerName: values.customerName,
CansOut: values.cansOut,
JarsOut: values.jarsOut,
EmptyCansIn: values.emptyCansIn,
JarsIn: values.jarsIn,
Bottles: values.bottles,
Ice: values.ice
})
// make changes to database
batch.commit()
.then(() => {
console.log('Entry added!!!!!!!!!');
});
This will then allow you to list all of the entry dates in your database using something like:
firebase.firestore().collection('WaterCanData')
.get()
.then((querySnapshot) => {
querySnapshot.forEach(doc => {
const entryDate = doc.id;
// const customerEntriesRef = doc.ref.collection('Entries');
console.log('Entry date found: ' + entryDate);
}
});
If (as an example) you wanted to also find how many entries were linked to a given date, you would need to also query each subcollection (here the code gets a little more confusing).
firebase.firestore().collection('WaterCanData')
.get()
.then((querySnapshot) => {
const fetchSizePromises = [];
// for each entry date, get the size of it's "Entries" subcollection
querySnapshot.forEach(doc => {
const entryDate = doc.id;
const customerEntriesRef = doc.ref.collection('Entries');
// if this get() fails, just store the error rather than throw it.
const thisEntrySizePromise = customerEntriesRef.get()
.then(
(entriesQuerySnapshot) => {
return { date: entryDate, size: entriesQuerySnapshot.size }
},
(error) => {
return { date: entryDate, size: -1, error }
}
);
// add this promise to the queue
fetchSizePromises.push(thisEntrySizePromise)
}
// wait for all fetch operations and return their results
return Promise.all(fetchSizePromises);
})
.then((entryInfoResults) => {
// for each entry, log the result
entryInfoResults.forEach((entryInfo) => {
if (entryInfo.error) {
// this entry failed
console.log(`${entryInfo.date} has an unknown number of customers in its Entries subcollection due to an error`, entryInfo.error);
} else {
// got size successfully
console.log(`${entryInfo.date} has ${entryInfo.size} customers in its Entries subcollection`);
}
}
});
Using below code you can console every document id inside waterCanData collection. In your database you have only one document, then it will console your document id. (10042021)
firestore()
.collection('WaterCanData')
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id)
});
})
I am trying to update several Firestore documents, based on the result of a third-party service inside a transaction. Problem is, I am getting the following error:
Error: Cannot modify a WriteBatch that has been committed.
Here is my code:
export default async function debitDueTransactions(context: any) {
const now = new Date().getTime();
return db.runTransaction(async (transaction: FirebaseFirestore.Transaction) => {
const chargesToCaptureRef = db.collection(`charges_to_capture`)
.where('dateToCapture', '>=', now)
.where('dateToCapture', '<=', (now + 86400000))
.where('captureResult', '==', null);
return transaction.get(chargesToCaptureRef).then((chargeToCaptureQuerySnap: FirebaseFirestore.QuerySnapshot) => {
chargeToCaptureQuerySnap.forEach(async (doc: FirebaseFirestore.QueryDocumentSnapshot) => {
const chargeToCapture = <ChargeToCapture>doc.data();
chargeToCapture.id = doc.id;
let errorKey = null;
// Calling third party service here, waiting response
const captureResult = await captureCharge(chargeToCapture.chargeId).catch((error: any) => {
errorKey = error.code ? error.code : 'unknown_error';
});
transaction.update(doc.ref, { captureResult: captureResult, errorKey: errorKey });
});
return new Promise((resolve) => { resolve(); });
})
});
}
Can't get what I am doing wrong, any idea ?
As you can see from the API documentation, transaction.get() only accepts a DocumentReference type object. You're passing it a Query object. A Firestore transaction isn't capable of transacting on a Query. If you want to transact on all the documents returned from a Query, you should perform the query before the transaction, then use transaction.get() on each DocumentReference individually.
In other words, I'm trying to figure out what is the Firestore equivalent to this in SQL:
UPDATE table SET field = 'foo' WHERE <condition>`
Yes, I am asking how to update multiple documents, at once, but unlike the linked questions, I'm specifically asking how to do this in one shot, without reading anything into memory, because there's no need to do so when all you want is to set a flag on all documents matching a condition.
db.collection('table')
.where(...condition...)
.update({
field: 'foo',
});
is what I expected to work, CollectionReference doesn't have an .update method.
The
Transactions and Batched Writes documentation mentions transactions and batched writes. Transactions are out because "A transaction consists of any number of get() operations followed by any number of write operations" Batched writes are also not a solution because they work document-by-document.
With MongoDB, this would be
db.table.update(
{ /* where clause */ },
{ $set: { field: 'foo' } }
)
So, can Firestore update multiple documents with one query, the way SQL database or MongoDB work, i.e. without requiring a round-trip to the client for each document? If not, how can this be done efficiently?
Updating a document in Cloud Firestore requires knowings its ID. Cloud Firestore does not support the equivalent of SQL's update queries.
You will always have to do this in two steps:
Run a query with your conditions to determine the document IDs
Update the documents with individual updates, or with one or more batched writes.
Note that you only need the document ID from step 1. So you could run a query that only returns the IDs. This is not possible in the client-side SDKs, but can be done through the REST API and Admin SDKs as shown here: How to get a list of document IDs in a collection Cloud Firestore?
Frank's answer is actually a great one and does solve the issue.
But for those in a hurry maybe this snippet might help you:
const updateAllFromCollection = async (collectionName) => {
const firebase = require('firebase-admin')
const collection = firebase.firestore().collection(collectionName)
const newDocumentBody = {
message: 'hello world'
}
collection.where('message', '==', 'goodbye world').get().then(response => {
let batch = firebase.firestore().batch()
response.docs.forEach((doc) => {
const docRef = firebase.firestore().collection(collectionName).doc(doc.id)
batch.update(docRef, newDocumentBody)
})
batch.commit().then(() => {
console.log(`updated all documents inside ${collectionName}`)
})
})
}
Just change what's inside the where function that queries the data and the newDocumentBody which is what's getting changed on every document.
Also don't forget to call the function with the collection's name.
The simplest approach is this
const ORDER_ITEMS = firebase.firestore().collection('OrderItems')
ORDER_ITEMS.where('order', '==', 2)
.get()
.then(snapshots => {
if (snapshots.size > 0) {
snapshots.forEach(orderItem => {
ORDER_ITEMS.doc(orderItem.id).update({ status: 1 })
})
}
})
For Dart / Flutter user (editted from Renato Trombini Neto)
// CollectionReference collection = FirebaseFirestore.instance.collection('something');
// This collection can be a subcollection.
_updateAllFromCollection(CollectionReference collection) async {
var newDocumentBody = {"username": ''};
User firebaseUser = FirebaseAuth.instance.currentUser;
DocumentReference docRef;
var response = await collection.where('uid', isEqualTo: firebaseUser.uid).get();
var batch = FirebaseFirestore.instance.batch();
response.docs.forEach((doc) {
docRef = collection.doc(doc.id);
batch.update(docRef, newDocumentBody);
});
batch.commit().then((a) {
print('updated all documents inside Collection');
});
}
If anyone's looking for a Java solution:
public boolean bulkUpdate() {
try {
// see https://firebase.google.com/docs/firestore/quotas#writes_and_transactions
int writeBatchLimit = 500;
int totalUpdates = 0;
while (totalUpdates % writeBatchLimit == 0) {
WriteBatch writeBatch = this.firestoreDB.batch();
// the query goes here
List<QueryDocumentSnapshot> documentsInBatch =
this.firestoreDB.collection("student")
.whereEqualTo("graduated", false)
.limit(writeBatchLimit)
.get()
.get()
.getDocuments();
if (documentsInBatch.isEmpty()) {
break;
}
// what I want to change goes here
documentsInBatch.forEach(
document -> writeBatch.update(document.getReference(), "graduated", true));
writeBatch.commit().get();
totalUpdates += documentsInBatch.size();
}
System.out.println("Number of updates: " + totalUpdates);
} catch (Exception e) {
return false;
}
return true;
}
Combining the answers from Renato and David, plus async/await syntax for batch part. Also enclosing them a try/catch in case any promise fails:
const updateAllFromCollection = async (collectionName) => {
const firebase = require('firebase-admin');
const collection = firebase.firestore().collection(collectionName);
const newDocumentBody = { message: 'hello world' };
try {
const response = await collection.where('message', '==', 'goodbye world').get();
const batch = firebase.firestore().batch();
response.docs.forEach((doc) => {
batch.update(doc.ref, newDocumentBody);
});
await batch.commit(); //Done
console.log(`updated all documents inside ${collectionName}`);
} catch (err) {
console.error(err);
}
return;
}
I like some of the answers but I feel this is cleaner:
import * as admin from "firebase-admin";
const db = admin.firestore();
const updates = { status: "pending" }
await db
.collection("COLLECTION_NAME")
.where("status", "==", "open")
.get()
.then((snap) => {
let batch = db.batch();
snap.docs.forEach((doc) => {
const ref = doc.ref;
batch.update(ref, updates);
});
return batch.commit();
});
It uses batched updates and the "ref" from the doc.
If you have already gathered uids for updating collections, simply do these steps.
if(uids.length) {
for(let i = 0; i < uids.length; i++) {
await (db.collection("collectionName")
.doc(uids[i]))
.update({"fieldName": false});
};
};