Home > Blockchain >  How to find and print array of objects in mongoDB document
How to find and print array of objects in mongoDB document

Time:05-27

I have this document in mongoDB:

{
  "_id": {
    "$oid": "628f739398580cae9c21b44f"
  },
  "events": [
    {
      "eventName": "Dans",
      "eventText": "Danse",
      "eventDate": "010101"
    },
    {
      "eventName": "Spill",
      "eventText": "Spille",
      "eventDate": "020202"
    }
  ],
  "school": "Høyskolen Kristiania"
}

I am trying to get each event (name, text and date) in their own div, but can't seem to access each "block" by their own. They are supposed to be printed as one, and only where school matches, and my intention was to make different documents for each school and filter by query from there. That though, is not an issue. I am able to get all of them as one array of objects or like

{
[dev:server]     _id: new ObjectId("628f739398580cae9c21b44f"),
[dev:server]     events: [ [Object], [Object] ],
[dev:server]     school: 'Høyskolen Kristiania'
[dev:server]   }

My API currently looks like this: Name of course is going to be sent in by userinfo, hardcoded for testing purposes.

router.get("/", async (req, res) => {
    const name = "Høyskolen Kristiania";

    const schools = await mongoDatabase
      .collection("tempschool")
      .find()
      .toArray();

    console.log(schools);

    res.json(schools);
  });

And my client:

function EventCard({ event }) {
  const { eventName, eventDate, eventText } = event;

  return (
    <div>
      <h1>{eventName}</h1>
      <h3>{eventDate}</h3>
      <div>{eventText}</div>
    </div>
  );
}

export function SchoolPage() {
  const {loading, error, data} = useLoader(
      async () => await fetchJSON("/api/schools")
  );

  const school = data;

  if (loading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return (
        <div>Error</div>
    );
  }

  return (
      <div>
        {school.map((event) => (
            <div key={event.name}>
              <EventCard event={event}/>
            </div>
        ))}
      </div>
  );
}

CodePudding user response:

I don't know if you've created tempschool as a MongooseSchema or not. You should though, you will then query it as
const school = await TempSchool.findOne({school: "Høyskolen Kristiania"});
school.events will then give you an array of objects. You will use it on front-end as

return(
    <div>
      school.events.map((event) => (
              <div>
              <h1>{event.eventName}</h1>
              <h3>{event.eventDate}</h3>
              <div>{event.eventText}</div>
              </div>
              )
          )
    </div>
);
  • Related