Reputation: 13
I cannot figure out for the life of me how PackId
is undefined
according to the error: TypeError: Cannot read property 'PackId' of undefined
.
What I'm doing here is: I'm deleting an object that's inside of a collection (which's happening successfully) but I'd also like to eventually display the response correctly which should consist of packIdsOwned
and packsOwnedMetadata
arrays being populated.
Why's PackId
null in the packIdsOwned.push(packsOwned[i].PackId);
line and how can I fix it?
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
});
}
Upvotes: 0
Views: 33
Reputation: 207501
You remove the index and than you are trying to read that element you just removed.
let removePackId = packsOwned.splice(i, 1); <-- You remove it
packIdsOwned.push(packsOwned[i].PackId); <-- You try to read it.
Upvotes: 1