Reputation: 1055
I have been working in the LAMP stack for years and am struggling to wrap my head around advanced querying with Firebase and NoSQL databases. I would like to return 5 random documents from a collection. Below is the VueJS code written thus far:
Here is the data object that I have created:
data () {
return {
courseIds: [],
}
}
Here is my created lifecycle hook where I'm querying the Firebase NoSQL database:
created() {
// fetch data from firestore
database.collection('courses').get()
.then(snapshot => {
snapshot.forEach(doc => {
let course = doc.data()
course.id = doc.id
this.courseIds.push(course.id)
})
})
}
Because I'm looking to randomize the data returned, I have added the beforeMount lifecycle hook which calls a Fisher-Yates shuffle method. The plan was to shuffle the returned data and then return only the first 5 documents:
beforeMount() {
this.courseIds = this.shuffle(this.courseIds)
}
And the method:
methods: {
shuffle: function(array) {
var m = array.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
}
I'm a slow learner, so more than likely this is a numbskull approach to the problem. My present issue is that Firebase is returning the Ids as an object rather than an array so my shuffle method isn't working as anticipated. See the console.log()
below:
[__ob__: Observer]
0: "0HnqJ8zZg1Rs3D4qod4l"
1: "1gZmoUpCOSDeLsYMDi4v"
2: "JrJj3a84qKTD72ncvGXd"
3: "LWMbY98m3sKLrHNDSUkW"
4: "SUn1kxHzMo7fu5urpNB5"
5: "kQRWQIj0mFXIWVJcaouY"
length: 6
__ob__: Observer {value: Array(6), dep: Dep, vmCount: 0}
__proto__: Array
Does anybody have a better approach to this functionality, or a good way to convert the courseIds into an array to be shuffled?
Upvotes: 0
Views: 79
Reputation: 83093
What happens if you do a bit differently, as follows:
created() {
// fetch data from firestore
database.collection('courses').get()
.then(snapshot => {
let courseIdsArray = [];
snapshot.forEach(doc => {
courseIdsArray.push(doc.id);
});
this.courseIds = courseIdsArray;
});
}
Upvotes: 1