Firestore get path of already queried document - javascript

I am trying to get the path of a queried document in Firebase Firestore. This is my code:
const location = await db.doc('/locations/US/regions/IOWA').get()
console.log(location.path)
However location.path returns undefined.
location.id works and returns the id.
I have used this as a resource: https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#path

When you call get() on a DocumentReference, you get back a DocumentSnapshot, which does not have a path property.
You're probably looking for location.ref.path.

The API documentation for DocumentSnapshot says that the reference of the document can be found in its reference property. So you will want to use this: doc.reference.

The currently accepted answer appears to be outdated, as aDocumentSnapshot does now store the path.
Every DocumentSnapshot has a DocumentReference found under the ref property (https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentSnapshot#ref)
In the DocumentSnapshot, you can then find a string representation of the path under the path property` (https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentReference#path)
In short, you can simply use doc.ref.path to get the path.

I know it is old and answered question, this is how I get the document reference from queried document
d.get()
.then(td=>{
let taskDep = td.data()
taskDep.id = td.id
taskDep.ref = td.ref
})

Related

How do you add multiple documents at once to a collection in Firestore?

I am somewhat new to Firebase and looking for the ability to write multiple JSON objects into a collection under random IDs in one operation. I am just using firestore and auth(not shown) along with react.
So far I have
Function TestDocs () {
{addDoc(collection(db, 'randomData'), {**object 1 example data**},{**object 2 more example data**}
)
}
I have a button on a webpage which adds the data into the DB. When I check Firestore only the first object is loaded and not the second... on top of this, assuming that I wanted to add hundreds of objects(not just 2), how would I go about this?
I was looking through the documentation for Firestore batch writes but it only lists set(), update() and delete() as permitted operations so I am not sure how it would work. Thanks in advance
You'll want to do this in two steps:
Create a reference to a new document with a new unique ID:
// Generate two new document references with a generated ids
const newRef1 = doc(collection(db, "randomData"));
const newRef2 = doc(collection(db, "randomData"));
Write to that reference in your batch or transaction.
Also see:
Firestore - batch.add is not a function (which contains the older namespaced syntax for doing the same).
The last snippet in the documentation on adding a document, which shows this approach.
I found another way to do this without using Firebases batch function. Each transaction or batch of writes can write to a maximum of 500 documents. I was looking to update my app with more than 500 and found a video on YouTube showing another way to do this.
I had to tweak the script a bit to get what I needed but the idea is there.
https://www.youtube.com/watch?v=Qg2_VFFcAI8

Sequelize - setting property of an instance does nothing?

I've used the standard instance syntax before without issue, but in this part of my code I can't seem to update an instance I've fetched from the database.
...
const instance = await db.models.Users.findOne({where: {profileName: foundChange.profileName}});
instance.profileName = webUser.username;
await instance.save()
console.log(`Profilename: ${instance.profileName}`);
Console returns the value it was before setting.
I've also tried instance.set(key, value) which similarly has no effects. Am I missing something?
I've found that directly addressing instance.dataValues will change it, but that seems to go against the Sequelize documentation. Will this way update properly?
I think it's because I'm trying to update the primary key actually! Probably a sign I should do some remodelling...

Why ref.getCollections() is not recognized as a function?

I'm doing a website which store users data on cloud firestore. I use this to get all subcollections of a user document once:
db.collection('users').doc(userID).getCollections().then( collections => {
/*I get my collections and I enjoy it :D*/
})
The problem is that this function is not recognized. I find this message on the console:
TypeError: db.collection(...).doc(...).getCollections is not a function
I know I could get the all subcollections otherwise but I want to save the maximum of readings because of de limited quota. All others firebase functions work in my project (like get() or set()) and getCollections() is in the documentation.
Thank for your help !
Google team was replaced method name from 'getCollections' to 'listCollections'. So you should update this method name again.
Reference at here https://googleapis.dev/nodejs/firestore/latest/DocumentReference.html#listCollections
It works for me with these tool versions: firebase-tools v7.2.1, firebase-admin v8.3.0, firebase-functions v3.2.0.
In your example db.collection('users').doc(userID) returns DocumentReference
and as far I can see DocumentReference object doesn't support getCollections method
Here is the documentation https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference

QueryDocumentSnapshot seems to lack the methods of its parent class

I'm using firebase to build a database application. I'm trying to get the firebase generated id of a particular document. The document is returned as a Promise, which returns a QuerySnapshot. A forEach loop pulls each QueryDocumentSnapshot out of the QuerySnapshot, so I'm working with the QueryDocumentSnapshot class. The documentation says that this class has the same API surface as the DocumentSnapshot class.
https://developers.google.com/android/reference/com/google/firebase/firestore/QueryDocumentSnapshot
Since the DocumentSnapshot class has a getId() method, I thought I'd use that.
searchBooks(){
this.booksSearched = true;
this.bookService.getBookList(this.authorName).get().then(bookListSnapshot =>{
this.bookList = [];
bookListSnapshot.forEach( snap =>{
this.bookList.push({
authorLastName: snap.data().authorLastName,
title: snap.data().title,
edition: snap.data().edition,
id: snap.getId() <-------ISSUE HERE-----------
});
return false;
});
});
}
However, I get this error.
property 'getId' does not exist on type 'QueryDocumentSnapshot'
Here is the code for the bookService
getBookList(authorLastName): firebase.firestore.Query{
return this.bookListRef.where("authorLastName", "==", authorLastName);
}
What's even more wild is when I tried change my code around. Instead of pulling the QueryDocumentSnapshots out using the forEach loop, I thought I would take advantage of the fact that bookListSnapShot is a QuerySnapshot and call its getDocuments() method. https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/QuerySnapshot
This would return a list of DocumentSnapshots, possibly meaning that whatever inheritance issue with the getId() method could be avoided. However, when I tried, I got this error:
var documents = bookListSnapshot.getDocuments();
Property 'getDocuments' does not exist on type 'QuerySnapshot'
To me, it seems like the documentation is being contradicted by the errors the editor is throwing. Does anyone know what's going on?
Thank you for reading,
-Joel
You're writing code in JavaScript, but you're looking at API documentation for Android using Java. Here are the JavaScript API docs for DocumentSnapshot and QueryDocumentSnapshot. DocumentSnapshot has a property called id that you're looking for.

Can we set cursor as a session variable?

I tried to set a cursor as a session variable looks like it is not working.
Anyone has idea about it ??
My Code:
Meteor.call('apiresult',function(e,result)
{
console.log(result);
Session.set("object",result)
});
//getting variable
var abc=Session.get("object");
return abc.skimlinksProductAPI.numFound;
looks like it's not working
Cursors can actually be stored in Session... sometimes. open the leaderboard app and try this in the browser console:
> Session.set('mycursor', Players.find());
undefined
> Session.get('mycursor')
LocalCollection.Cursor {collection: LocalCollection, selector_f: function, sort_f: null, skip: undefined, limit: undefined…}
> Session.get('mycursor').fetch()
[Object, Object, Object, Object, Object]
Now download the code of the leaderboard example app, use the latest Meteor, and do the same thing in the browser console. You might get:
The moral of the story seems to be, don't store cursors in session variables. Store the Minimongo selector and options (sort, fields etc.) instead as objects.
Interesting thought. It would not be required though, because a cursor is already reactive. You can store the cursor in an ordinary variable.
One thing to point out though is you can't send cursors down using Meteor.call, you can send down javascript objects or specify your own EJSON but you couldn't do this with cursors.
So you can store cursors in global variables if you do the .find() locally, but you cant do it on the server then transfer the cursor using Meteor.call
You can use a publish/subscribe function for this instead.

Categories