I was tasked with migrating data found in an array containing a series of arrays of objects within the documents of our Firestore database to a subcollection. The purpose of this migration was to improve the management of this information, making it easier to filter, edit, and delete this data. I developed a function to filter the documents that had some data within these arrays and soon found over 500 documents to migrate. To solve this problem, I developed a JavaScript logic that involved separating this data into an object called "data" and also obtaining the document's ID to which this data belonged. Then, I saved this data in the subcollection of the document with that ID.
Snippet of code to retrieve documents in the collection:
const q = query(
collection(db, "clientes"),
where("empresa", "!=", "teste")
);
const querySnapshot = await getDocs(q);
Snippet of code where i filter the necessary data from each document:
let clientes = [];
querySnapshot.forEach((doc) => {
const acessos = doc.data().acessos;
if (acessos && typeof acessos === "object") {
Object.entries(acessos).forEach(([categoria, objetos]) => {
if (Array.isArray(objetos)) {
objetos.forEach((objeto) => {
const {
email = "",
nome = "",
observacao = "",
senha = "",
} = objeto || {};
let cliente = {
id: doc.id,
razaoSocial: doc.data().razaoSocial,
categoria,
email,
nome,
observacao,
senha,
};
clientes.push(cliente);
});
} else {
const {
email = "",
nome = "",
observacao = "",
senha = "",
} = objetos || {};
let cliente = {
id: doc.id,
razaoSocial: doc.data().razaoSocial,
categoria,
email,
nome,
observacao,
senha,
};
clientes.push(cliente);
}
});
}
});
return clientes;
Function I used to retrieve and separate the data, and then register it in the subcollection with the registerAccess()
function:
async function fetchCustomersWithAccess() {
const result = await listCustomersWithAccess();
result.forEach((doc) => {
const data = {
categoria: doc.categoria,
email: doc.email,
nome: doc.nome,
observacao: doc.observacao,
senha: doc.senha,
};
const docId = doc.id;
registerAccess(docId, data);
});
}