I have the cars collection in firebase with the following format and examples:
{
{
make: BMW,
model: X7,
color: white
},
{
make: BMW,
model: X7,
color: white
},
{
make: BMW,
model: X7,
color: black
},
{
make: Audi,
model: Q7,
color: gray
}
}
What I would like to receive from my query is something like this:
[
{
make: BMW,
model: X7,
colors: [white, black]
},
{
make: Audi,
model: Q7,
colors: [gray]
}
]
It doesn't have to be exactly at this format but I hope that I made my purpose clear. How can I achieve this efficiently using firebase?
My code to receive all the documents:
const admin = require('firebase-admin')
const db = admin.firestore()
module.exports.getVehicles = async (data, context) => {
const vehiclesQuery = db.collection('vehicles').get()
const vehicles = []
vehiclesQuery.forEach(doc => {
vehicles.push(doc.data())
})
return vehicles
}
There isn't any direct way to get data in that format. You would have to modify the data using Javascript after fetching all the documents. Also you are missing the await before get() statement:
module.exports.getVehicles = async (data, context) => {
const vehiclesQuery = await db.collection('vehicles').get()
const res = {}
vehiclesQuery.docs.forEach(doc => {
const { color, make, model } = doc
if (!res[make+'-'+model]) {
res[make+'-'+model] = [color]
} else {
res[make+'-'+model].push(color)
}
})
const vehicles = []
Object.entries(res).forEach((v) => {
const [make, model] = v[0].split('-')
vehicles.push({make, model, colors: v[1]})
})
console.log(vehicles)
return vehicles
}