Guide on how to set a timestamp for an array type document object in Firebase

I am currently working on a Vue.js application that allows for dynamic addition of items to an array in Cloud Firestore. The array, named events, consists of various objects including a timestamp. Below is the function I am using:

let newDetails = this.newDetails
let newImage = this.imageUrl
let timestamp = moment(Date.now()).format('lll')
let ref = db.collection('users').where('user_id', '==', firebase.auth().currentUser.uid)
    .get()
    .then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
            console.log(doc.id, ' => ', doc.data())
            doc.ref.update({
                'events': firebase.firestore.FieldValue.arrayUnion({
                    'name': doc.data().name,
                    'details': newDetails,
                    'image': newImage,
                    'timestamp': moment(Date.now()).format('lll')
                })
            })
        })
    })

My objective is to display each item in the array on the UI, sorted according to their timestamps. I initially tried implementing the following Vuex action (shown below again) with an .orderBy() method to achieve this sorting:

setCurrentUser: async context => {
    let ref = db.collection('users').orderBy('events')
    let snapshot = await ref.where('user_id', '==', firebase.auth().currentUser.uid).get()
    const users = []
    snapshot.forEach(doc => {
        let currentUserData = doc.data()
        currentUserData.id = doc.id
        users.push(currentUserData)
    })
    context.commit('setCurrentUser', users)
},

However, I realize that arranging these items based on timestamps within array type document may not be feasible. Any suggestions on how to assign a timestamp to each array item in Firestore without making it a separate array object, so as to maintain ordering based on timestamp?

Answer №1

If you're looking for information on data-types in Cloud Firestore, check out this link: https://firebase.google.com/docs/firestore/manage-data/data-types

One solution to sorting events based on the timestamp is to use a Map.

Solution 1: Map<Timestamp, Event> In this approach, Timestamp can be used as the key if there are no events happening simultaneously. Setting the key as Timestamp is essential because Cloud Firestore sorts the Map by Key first and then by Value.

Solution 2: If multiple events can occur for a user at the same time, then Event can be used as the key. The map would look like this: Map<Event,Timestamp>, and you can sort based on values after fetching the Map from Firestore.

Solution 3: Another option is to store all events in a separate collection named Events with the documentId of each event serving as the key. In this case, the Map would be Map<String,Timestamp>. This could be a good choice if a user has many events.

I hope this explanation helps.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered while generating REST API through Postman resulting in a 500 error

I am in the process of creating a Node.js API for a web application. The GET request is functioning properly, however, when attempting to execute a POST request, I encounter an error messageError Below is the code snippet: //User Schema const mongoose ...

Dealing with multiple occurrences of forward slashes in a URL

Currently utilizing React and grappling with resolving duplicate forward slashes on my site in a manner similar to Facebook. The process functions as follows: For example, if the user visits: https://facebook.com///settings, the URL is then corrected to h ...

What is the method for obtaining command context in Chrome console through Selenium?

I attempted the code below, but unfortunately, it did not work for me. puts @driver.execute_script("window.dataLayer[0]") puts @driver.execute_script("console.log(window.dataLayer[0])") Manually entering "dataLayer" in the Chrome console displays the obj ...

Creating dynamic content in the Ajax-enabled Smart Admin theme: A step-by-step guide

As I work on developing an application for a client, my focus is on creating a web service using Laravel5 for the backend. To enhance the user interface of this web service, I have chosen to incorporate the Smart Admin Theme, specifically utilizing the Aja ...

Model-View-Controller architecture in Node.js backend

I recently delved into nodejs development and everything has been going smoothly so far. I have my nodejs server up and running using expressjs as the backend framework. However, I encountered a problem - most nodejs tutorials recommend creating a unique s ...

Open a new HTML page with jQuery with a click event trigger on an iframe element

Hello everyone, I have a simple question as I am still learning about Jquery. I am attempting to load another .html page whenever a figure element is clicked on this .html page. However, the script tag is not working as expected. Can someone please assist ...

When removing a class from a group of elements in JavaScript, it seems to only erase approximately fifty percent of the

I've been working on a Word Puzzle algorithm that involves displaying a set of words on a grid for users to solve. They can either attempt to solve the puzzle themselves or click a "solve" button, triggering a function to visually solve the Word Puzzl ...

Toggle the element within the selected row using Jquery

In order to create a client list, users must click on rows to select them and then submit the selections to the database for a cron job to send out emails. Instead of using checkboxes, I am attempting to highlight rows by including two hidden elements - o ...

`Changing the background according to the page URL in React JS: A guide`

Looking to enhance my simple app with a few pages by changing the background color based on page URL using React.js. What I aim to achieve: If the pathname is /movies, I want the background color to be red. This is my current progress: import React, { ...

What are the steps to install @vue/cli following the deprecation of the Request model in npm?

Currently dealing with Windows 10 and attempting to set up vue/cli by following the provided code from its documentation npm install -g @vue/cli Unfortunately, this code is not working as it produces an error message indicating: npm WARN deprecated [emai ...

Setting up Stylelint in a Vue 3 app with VSCode to automatically lint on save

I am looking to perform linting on my scss files and scss scope within .vue components. Here is what my configuration looks like in stylelint.config: module.exports = { extends: [ 'stylelint-config-standard', 'stylelint-config-rece ...

How can I extract a list of errors from this JSON object in a React.js application?

Is there a way to extract the list of errors from the following JSON object using React js? data = { "container_1587015390439_0001_01_000004": { "ERROR":["20/04/16 05:43:51 ERROR CoarseGrainedExecutorBackend: RECEIVED SIGNAL TERM"] , ...

How can I apply JavaScript to aggregate child node values and assign them to the parent in JSON data format?

I receive a dynamic JSON from the server, which has varying structures. Each data entry consists of a chapter with stages and/or review sets at the root level. If a stage exists, there will be either a review set array or another stage. The review set cont ...

Move the option from one box to another in jQuery and retain its value

Hey guys, I need some assistance with a jQuery function. The first set of boxes works perfectly with the left and right buttons, but the second set is not functioning properly and doesn't display its price value. I want to fix it so that when I click ...

Element Not Found Error: Element could not be located - Script using JavaScript with Seleniumwebdriver

After extensive research, I have identified the issue at hand. The challenge lies in the fact that others do not follow the same coding structure as me and are unclear about where or what to insert into my code. I am aware that a try/catch statement or t ...

Using a Javascript loop to showcase values from a database

As a Python developer who is new to JavaScript and AJAX, I am currently working on creating a pie chart that displays database values. $(document).ready(function () { google.charts.load('current', { 'packages': ['corechart&ap ...

Generating an associative array on the fly

I am interested in transforming a hash by creating nested keys and then adding another hash at the end. For example... var hash_a = {'foo': 'bar'} var hash_b = {'alpha': 'beta'} var array = ['a', 'b& ...

Enhancing Performance with Web Workers in Angular CLI

Lately, I've been tackling a challenging issue with my Angular app - heavy computation on the client side leading to UI blockage. My solution? Utilizing Web Workers in my Angular CLI project to separate UI tasks into one thread and heavy processing in ...

Displaying a div when a button is clicked (PHP)

Hello everyone, I'm new to posting here so please bear with me if I seem inexperienced. On my website, there is a button that needs to disappear when clicked and be replaced by a form without refreshing the page. I was able to accomplish this using ...

Is it possible to export multiple named exports in a single set without changing how variables are called?

In my constants file I have: export const CONSTANT1 = 'CONSTANT1'; export const CONSTANT2 = 'CONSTANT2'; export const CONSTANT3 = 'CONSTANT3'; export const CONSTANT4 = 'CONSTANT4'; export const CONSTANT5 = 'CONS ...