Difficulty pulling fields from collection with Node.js

In my Node.js server code, I retrieve the object from the collection, log it, but get ‘undefined’ when I try to log a field from the collection.
Here’s the code:

socket.on('saveHike', () => {        

        // save game stats
        async function saveHike() {

            console.log ('saving the Hike data');

            await Game.updateOne({},{ $set: { hikeEnd: Date.now() } });

            await Game.updateOne({},{ $set: { townStart: Date.now() } });

            var gameFind = await Game.find( { teamName: thisTeam } ); // grab this game's record

            console.log ('gameFind: ' + gameFind);

            console.log ('gameFind.teamName: ' + gameFind.teamName);

            console.log ('gameFind.hikeEnd: ' + gameFind.hikeEnd);




Console output:

gameFind: {
_id: new ObjectId(“62e1b6130b725fd445edd7b0”),
teamName: ‘a’,
captain: ‘s’,
score: 0,
startTime: 2022-07-27T22:02:59.022Z,
leavetakingsEnd: 2022-07-27T22:02:59.038Z,
hikeStart: 2022-07-27T22:02:59.042Z,
hikeVotes: 1,
hikeEnd: 2022-07-27T22:03:18.449Z,
townStart: 2022-07-27T22:03:18.453Z,
townEnd: 1970-01-01T00:00:00.000Z,
__v: 0

gameFind.teamName: undefined
gameFind.hikeEnd: undefined

I’m not getting why the object is clearly logged but calling the dot fields returns them as undefined. Any ideas would be greatly appreciated. Thanks in advance!

You should do the above in a single database access. You might be updating 2 completely different documents and with 2 different values of Date.now().

Since you do Game.find() with teamName:thisTeam, I suspect that you want to Game.updateOne() with the same query.

Finally, Game.find() returns a cursor but you seem to expect a document, I think you should be using Game.findOne().


Brilliant, that did the trick. Thanks much, Steeve!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.