Querying a collection by id of one of its members - google-cloud-firestore

A Firestore collection activities contains a field called member. That field is a Document Reference to a document in the members collection.
Is there a way to filter all activities for that member if all I have is the member document id?
E.g. something like:
firebase.collection('activities').where('member.id', '==', memberId)
The closest I got was
firebase.collection('activities').where('member', '==', firebase.collection('members').document(memberId)
but that constitutes an extra read operation.

This code firebase.collection('members').document(memberId) sets up a DocumentReference. It does not yet read that document, so there's no charge for it.
Your last snippet looks correct to me: to find all activities with a reference to a specific member, you need to set up a DocumentReference to that member's document.

Related

Firebase: Operation was rejected because the system is not in a state required for the operation's execution

I'm starting working with collections groups in Firebase and I cannot make it work. I need to filter it by billable leases:
users/portfolios/rents
Here I have a property which is a list of leases (not a collection, just a property) called leases with some properties like billable:
I have created a single-field index:
And also a composite index (not sure if I also need it):
This is my query using Flutter:
FirebaseFirestore.instance
.collectionGroup('rents')
.where('billable', isEqualTo: true)
.get()
.then((QuerySnapshot querySnapshot) {
for (var doc in querySnapshot.docs) {
print(doc);
}
});
The error I get is:
Operation was rejected because the system is not in a state required for the operation's execution. If performing a query, ensure it has been indexed via the Firebase console.
It's not indexed already?
For the query in your question you'll need a collection group index on the finished field of the rents collection group, which I don't see in any of the screenshots you shared.
From the screenshot of a document you linked in the comments here:
So billable is a value in each item of the leases array field. There is no way to query on such a single value in an array field, as the == operator checks whether the entire array field is the same as the value you specify, and the arrayContains operator checks if any array item matches the entire value you specify.
The common workaround is to extra the value you want to query on to a top-level field, either an array field or a single boolean. For example, if you add a field hasAnyBillableLeases to the rents document, you can query on that.
Alternatively, put the leases in their own subcollection, so that each lease becomes its own document and then can then query its billable field.

NoSQL/MongoDB: When do I need _id in nested objects?

I don't understand the purpose of the _id field when it refers to a simple nested object, eg it is not used as a root entity in a dedicated collection.
Let's say, we have a simple value-object like Money({currency: String, amount: Number }). Obviously, you are never going to store such a value object by itself in a dedicated collection. It will rather be attached to a Transaction or a Product, which will have their own collection.
But you still might query for specific currencies or amounts that are higher/lower than a given value. And you might programmatically (not on DB level) set the value of a transaction to the same as of a purchased product.
Would you need an _id in this case? What are the cases, where a nested object needs an _id?
Assuming the _id you are asking about is an ObjectId, the only purpose of such field is to uniquely identify an object. Either a document in a collection or a subdocument in an array.
From the description of your money case it doesn't seem necessary to have such _id field for your value object. A valid use case might be an array of otherwise non-unique/non-identifiable subdocuments e.g. log entries, encrypted data, etc.
ODMs might add such field by default to have a unified way to address subdocuments regardless of application needs.

Firestore: get an Observable doc from another field which is not the Id

I want to get a single Observable from a collection, but I want to get it from a different field that is not the id. It is possible?
I do not want to do a query and limit to 1. I need to get a Single Observable not an array Observable.
Schema:
Code:
this.afs.doc<Credit>('credits/uid/'+ uid).valueChanges();
Error:
Invalid document reference. Document references must have an even number of segments, but credits/uid/d1Zt8sozYqb6H27lhoJgF1Gx2Cc2 has 3
I am not sure if I understand correctly, but I guess that you want to get document with particular uid field value, not using document id.
This particular error is related with common feature of Firestore, that every document has to be in collection not in document. So path values for documents, (nested as well) are always checked, if the segments (devided by /) number is even ex. collection1/doc1/collection2/doc2/collection3/doc3
As results in your code we have 3 segments (like credits/uid/<uid_value>) so this is the error.
I am not very familiar with angularFire2 itself, but I have done it in JS. The approach is normally to query collection and than use method on the results, which in classic JS returns Query object on which the same methods can be used as on CollectionReference (which extends 'Query' btw - reference 1).
Combining this approach with those references: querying and collection I propose following solution:
this.afs.collection('credits', ref => ref.where('uid', '==', <uid_value>)).valueChanges()
If uid_value will be unique you should get your doc.
Unfortunately I do not have any playground to test the solution so please let me know how it works - or if there will be any additional errors.
I hope it will help! Good Luck!

mongodb find documents with field from other collection

I have two collection on stores user data and another stores all invitations.
In invitation collection I only store two ids one is fromID and another is toID
I am able to get all the document array from invitations collection, but how to get the user detail from user collection.
Thanks
MongoDB isn't a relational database and isn't the best choice to store such data. That being said, you can use the $lookup function as part of an aggregate query. See the docs, here.
You can use populate to get user detail. that is assuming in your mongoose model you made the toID and fromID of type mongoose model and you set the correct ref. check the docs. http://mongoosejs.com/docs/populate.html

Mongodb, get full object from a reference

Does exist anything permitting us to access a full object from a reference with Mongodb ?
For example, I have a User and a Type collection. A user has a Type, stored with a reference to the Type object.
Is it possible to access the full User object with the Type, without lazyloading it ?
Thanks for all
Yes; if you're happy making use of mongoose, then you can use its populate() function:
Populated paths are no longer set to their original _id , their value is replaced with the mongoose document returned from the database by performing a separate query before returning the results.
http://mongoosejs.com/docs/populate.html
So for your User, when performing a query to derive said user, something like this would set up the Type instance:
User.findOne({ username: 'Fred Bloggs' }).populate('type')
.exec(function (err, user) {
...
MongoDB does not do joins. It's not possible to get the information to embed the full Type object in the User document without more than one operation (I guess you have to "lazyload" it, in your terminology). The Mongoose populate() function just handles doing the extra queries and replacing the id with the document for you - it does multiple queries just like any other client doing the same operation would have to. You should think carefully about what types of queries you are doing to determine if it might be a good idea to denormalize the Type object into User documents.