In my Node.js code, the server console returns the object gameFind with a populated value for hikeEnd (it’s a Date field), but the console result for gameFind.hikeEnd, called immediately after, is undefined. This makes my equation NaN. What am I doing wrong here?
async function saveHike() {
await Game.updateOne({},{ $set: { hikeEnd: Date.now() } });
var gameFind = await Game.find( { teamName: thisTeam } );
console.log ('gameFind: ' + gameFind);
console.log ('gameFind.hikeEnd: ' + gameFind.hikeEnd);
//calculate the score
var hikeScore = (gameFind.hikeEnd - gameFind.hikeStart) / 1000;
console.log ('hikeScore: ' + hikeScore);
}
saveHike();
EDIT: console.log output
gameFind: {
_id: new ObjectId("62df29b4ea65773e6827aa54"),
teamName: 'a',
captain: 's',
score: 0,
startTime: 2022-07-25T23:39:32.235Z,
leavetakingsEnd: 2022-07-25T23:39:32.248Z,
hikeStart: 2022-07-25T23:39:32.252Z,
hikeVotes: 1,
hikeEnd: 2022-07-25T23:39:53.835Z,
townStart: 2022-07-25T23:39:53.838Z,
townEnd: 1970-01-01T00:00:00.000Z,
__v: 0
}
hikeEnd: undefined
hikeScore: NaN
Given Seth’s comments, I suppose this must be an async/await issue, but I cannot determine it. I have tried calling it with gameFind[hikeEnd] rather than a dot call but it still logs undefined. Is await Game.find being executed AFTER the console.logs because it’s in an await? This must be it, but I can’t remedy it. Thanks in advance, this has gotten quite frustrating.
2
Answers
The ultimate solution was to change my
Game.find
toGame.findOne
so it returns a document rather than a cursor.I made a version of your code that doesn’t execute from the database just to see if I could mirror your output. I cannot.
Here is my code,
And here is my output
gameFind:
gameFind.hikeEnd: Mon Jul 25 2022 16:39:53 GMT-0700 (Pacific Daylight Time)
hikeScore: 21.583
What’s likely happening for you is gameFind.hikeEnd is undefined because gameFind doesn’t have a field called hikeEnd on it.