简体   繁体   English

如何在 mongoDB 文档中查找和打印对象数组

[英]How to find and print array of objects in mongoDB document

I have this document in mongoDB:我在 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.我试图在他们自己的 div 中获取每个事件(名称、文本和日期),但似乎无法自己访问每个“块”。 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.我的 API 目前看起来像这样: 当然名称将由 userinfo 发送,硬编码用于测试目的。

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>
  );
}

I don't know if you've created tempschool as a MongooseSchema or not.我不知道您是否将tempschool创建为MongooseSchema 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.然后school.events会给你一个对象数组。 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>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM