UCProgrammer
UCProgrammer

Reputation: 557

Properties on awaited variable storing an object showing as undefined

I am trying to use some data that I get back from my mongodb atlas database and then use that data to perform another query. The calling function, selectGoalsForEpic(), calls and awaits findEpic(id). From the console.log statement I have in findEpic, I know that a valid object was found. My console.log statement after findEpic() call even shows [object Object] was returned and not undefined. I'm not sure why js doesn't allow you to view the contents of this variable here but that is beyond the scope of this question I guess. Anyway my next console statement says that epic.goals is undefined and my next query results in an error because of this. I thought await was supposed to pause execution and get the return value from a resolved promise but that doesn't appear to be the case here. Can someplease please explain to me what is going on here? Thanks

 export const selectGoalsForEpic= async (id:string) => {
    console.log("id is " + id);
    const epic = await findEpic(id);
    console.log("here epic" + epic);
    console.log("EPIC " + epic.goals);
    const goals = goalsCollection.find({_id:{$in: epic.goals}})
        .toArray()
        .then(res => {
            return res;
        })
        .catch(err => {
            console.log(`${FIND_EPIC_RESULT}: ${err}`);
        });
    return goals;
};

export const findEpic = (id:string):any => {
    const epic = epicCollection.find({_id:{$oid: id}})
        .toArray()
        .then(res => {
            console.log(res);
            return res;
        })
        .catch(err => {
            console.log(`${FIND_EPIC_RESULT}: ${err}`);
        });
    return epic;
};

// somewhere else calls 
selectGoalsForEpic(my_id)

Upvotes: 0

Views: 39

Answers (1)

Guerric P
Guerric P

Reputation: 31825

Use console.log("here epic", epic); so that doesn't display [object Object]. That will give you indications on why epic.goals is undefined

Upvotes: 1

Related Questions