I'm building a simple chat application using Firebase and Firestore. The pseudo-schema I have in my mind looks like this:
• threads: collection
|
+---- • friend_id: str
• last_messaged: timestamp
• messages: collection
|
+---- • sender_id: str
• text: str
• timestamp: timestamp
Now, lets say my friend with an id of 420
messages me for the first time. I would want to store this data by creating a new thread. Lets say I do this using the following command:
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
var thread_id = '212';
var message_id = '3498213712';
db.collection('threads').add({
id: thread_id,
friend_id: '420',
last_messaged: 1557862539,
messages: [
{
id: message_id,
sender_id: '420',
text: 'Hello',
timestamp: 1557862539
}
]
})
Is this the right way to do things? Would a collection called messages
be automatically created since I'm sending a JSON object in that field? If not, how can I do this the right way?
EDIT: Perhaps I was not clear enough earlier. I want messages
to be a sub-collection
. Right now, it is an array, according to a comment below.
EDIT2: Both threads
id and messages
are not random. Update the code to reflect that.
NOT DUPLICATE: Not a duplicate of the question linked in the comments because that question is for Java and the Android SDK, while this one is for Javascript.