Iterating through multiple documents

Issue

I’m running into some difficulties iterating through a list of documents. I’m working on an app for distributing season tickets amongst friends and I’ve created a document store in mongodb. When I post the teamId and number of tickets (groups) it creates a document with the below structure.

{
  draftOwner: '',
  draftState: 'active',
  draftCreate: 1659240148635,
  draftGroups: 2,
  homeTeam: '',
  homeId: 17,
  draftInvites: '',
  homeSchedule: [
    {
      date: '2022-10-14T23:30:00Z',
      home_id: 17,
      home_name: 'Detroit Red Wings',
      away_id: 8,
      away_name: 'Montréal Canadiens',
      ticketName_0: '',
      ticketOwner_0: '',
      ticketName_1: '',
      ticketOwner_1: ''
    },
    {
      date: '2022-10-17T23:30:00Z',
      home_id: 17,
      home_name: 'Detroit Red Wings',
      away_id: 26,
      away_name: 'Los Angeles Kings',
      ticketName_0: '',
      ticketOwner_0: '',
      ticketName_1: '',
      ticketOwner_1: ''
    },
    {
      date: '2022-10-23T21:00:00Z',
      home_id: 17,
      home_name: 'Detroit Red Wings',
      away_id: 24,
      away_name: 'Anaheim Ducks',
      ticketName_0: '',
      ticketOwner_0: '',
      ticketName_1: '',
      ticketOwner_1: ''
    }, ... ]

Example of my post method that creates documents for reference.

const createDraft = (req, res, next) => {

    const teamId = parseInt(req.query.id);
    const draftGroups = parseInt(req.query.groups);

    const url = nhlScheduleAPI + teamId.toString() + season;
    let settings = { method: "Get"};

    fetch(url, settings)
        .then(res => res.json())
        .then((json) => {
            let games = json['dates'];
            let draftSchedule = [];

            for (let i = 0; i < games.length; i++) {
                let row = {};
                if (games[i]['games'][0]['teams']['home']['team']['id'] === teamId) {
                    Object.assign(row, {date: games[i]['games'][0]['gameDate']});
                    Object.assign(row, {home_id: games[i]['games'][0]['teams']['home']['team']['id']});
                    Object.assign(row, {home_name: games[i]['games'][0]['teams']['home']['team']['name']});
                    Object.assign(row, {away_id: games[i]['games'][0]['teams']['away']['team']['id']});
                    Object.assign(row, {away_name: games[i]['games'][0]['teams']['away']['team']['name']});

                    for (let n = 0; n < draftGroups; n++) {
                        let ticketName = "ticketName_" + n.toString();
                        let ticketOwner = "ticketOwner_" + n.toString();
                        Object.assign(row, {[ticketName]: ""})
                        Object.assign(row, {[ticketOwner]: ""})
                    }
                    draftSchedule.push(row);
                }
            }

            let newDraftObj = new Object({ draftOwner: "", draftState: "active", draftCreate: Date.now(),
                draftGroups: draftGroups, homeTeam: "", homeId: teamId, draftInvites: "", homeSchedule: draftSchedule });

            const client = new MongoClient(uri);

            async function run() {
                try {
                    const database = client.db("ticketdrafterDB");
                    const drafts = database.collection("drafts");
                    const result = await drafts.insertOne(newDraftObj);
                    console.log(result);
                    console.log(newDraftObj);
                } finally {
                    await client.close();
                }
            }
            run().catch(console.dir);

            res.send(newDraftObj)
        })
};

So now what I am running into issues with is iterating through the list of the currently {draftState: active} drafts. I’m trying to show a page that just has a table output of each object showing [draftCreate, homeTeam, draftOwner]. Here is what I have created so far and I’m getting console output, so the objects are being retrieved but I just can’t display them to the client for some reason.

controller/home.js

const homeView = (req, res, next) => {
    const client = new MongoClient(uri);

    async function run() {
        try {
            const database = client.db("ticketdrafterDB");
            const collection = database.collection("drafts");

            const query = { draftState: "active" };
            const options = { projection: { homeSchedule: 1 }};

            const drafts = collection.find(query, options);

            if ((await drafts.count()) === 0) {
                console.log("No documents found!")
            }
            
            res.render('index', {drafts: drafts});
        } finally {
            await client.close();
        }
    }
    run().catch(console.dir);

index.pug

each draft in drafts
            li.list-group-item
              p #{draft.draftState}

Would really appreciate any guidance here, thanks in advance!

Solution

try turning the drafts cursor into an array with method toArray:

const results = await drafts.toArray();

res.render('index', {drafts: results});

Answered By – traynor

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published