I'm pretty sure I'm missing something obvious. I come from a traditional relational database background.
So every document has an Id. Is that Id needed to get that document back quickly, or is searching by a text field as efficient?
export abstract class FireBaseDoc {
id: string = ``;
}
export class NameModel extends FireBaseDoc {
first: string = ``;
last: string = ``;
email: string = ``;
}
I'm thinking in this case, I would create an index on email and search for a user that way since that's a unique field.
CodePudding user response:
Every document has an Id. Is that Id needed to get that document back quickly, or is searching by a text field as efficient?
The document ID is essentially a primary key like id
field most SQL database examples. You cannot create multiple document with duplicate ID in same collection. If you know the document ID, it's easy to get a single document as shown below:
await db.collection("[col_id]").doc("[doc_id]").get()
If you want to fetch a document by a field's value, then you would require a query:
await db.collection("[col_id]").where("field", "==", "value").get();
// Equivalent to:
// SELECT * FROM col WHERE field == "value";
If you are using any authentication service like Firebase Authentication, I would recommend using user's auth UID as document ID as its relatively easier to fetch a single document by ID instead of using a query and write security rules.
I would create an index on email and search for a user that way since that's a unique field.
Firestore does not support any UNIQUE INDEX
feature. Only way to ensure unique value for a field in document is to first to manually check if the value is used already or use it as the document ID.
Checkout Get to know Cloud Firestore series for a detailed explanation.