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?