No puedo entender por mi vida cómo PackId no está undefined de acuerdo con el error: TypeError: Cannot read property 'PackId' of undefined .
Lo que estoy haciendo aquí es: estoy eliminando un objeto que está dentro de una colección (lo que está sucediendo con éxito), pero también me gustaría mostrar la respuesta correctamente, que debería consistir en matrices packIdsOwned y packsOwnedMetadata que se completan.
¿Por qué PackId es nulo en packIdsOwned.push(packsOwned[i].PackId); línea y cómo puedo solucionarlo?
const db = client.db("myDb"); let collection = db.collection("Players"); let result = null; let packIdsOwned = []; let packsOwnedMetadata = []; let packIdInput = Profile.PackIdInput; // user input let packsOwned = result.packsOwned; // Delete object in the document collection.updateOne({"userName": result['userName']}, { $pull: { packsOwned: { PackId: packIdInput }}}); // Remove the pack ID from the response that's been deleted in the document for(let i = 0; i < packsOwned.length; i++) { if (packsOwned[i].PackId == packIdInput) { let removePackId = packsOwned.splice(i, 1); // find the PackId in the document and delete it removePackId = null; } // this is for the response but the below line is throwing off the whole program packIdsOwned.push(packsOwned[i].PackId); // it's saying this PackId value is null packsOwnedMetadata.push({ PackID : packsOwned[i].PackId }); }Elimina el índice y luego está tratando de leer ese elemento que acaba de eliminar.
let removePackId = packsOwned.splice(i, 1); <-- You remove it packIdsOwned.push(packsOwned[i].PackId); <-- You try to read it.