简体   繁体   English

如何访问 mongoose 填充字段?

[英]How to access mongoose populated fields?

I'm not able to access the populated fields of mongoose objects.我无法访问 mongoose 对象的填充字段。 I want to output it in my page.我想在我的页面中 output 它。

Example:例子:

"console.log(booking.assignedUser.first)" gives me back: “console.log(booking.assignedUser.first)”给我回了:

TypeError: Cannot read properties of undefined (reading 'first') TypeError:无法读取未定义的属性(读取“第一”)

But from what I can tell, this should be working.但据我所知,这应该有效。 The field is clearly there.该领域显然在那里。 在此处输入图像描述

In my jsx file:在我的 jsx 文件中:

console.log(booking.assignedUser)

在此处输入图像描述 Object: Object:

{
  etc etc

  assignedUser: { _id: new ObjectId("62f068b068802d58c8d35442"), first: 'driver' },
  etc etc
}

So why I can access booking.assignedUser and it shows me the data, but booking.assignedUser.first doesn't work?那么为什么我可以访问 booking.assignedUser 并显示数据,但 booking.assignedUser.first 不起作用?

Because these values are being populated from the DB, I guess they aren't loading fast enough so it's giving me this error.因为这些值是从数据库中填充的,所以我猜它们加载速度不够快,所以它给了我这个错误。

If I check to make sure the value exists first, then use it, it's working.如果我先检查以确保该值存在,然后使用它,它就可以工作。

I'm working with a lot of this type of data in my app, so instead of outputting the jsx directly in the react object, I'm using a function to return it all for me which I pass in the db data.我在我的应用程序中处理了大量此类数据,因此我没有直接在反应 object 中输出 jsx,而是使用 function 为我返回所有数据,我将这些数据传入数据库数据。

using a ternary at the beginning of the output within the React component was not good enough, for example.例如,在 React 组件中的 output 开头使用三元组就不够好。

{ data ?
<Form>
  <SomeStuffHere>
  <SomeMoreStuffHere>
  <Form.Control> {data.something} </Form.Control>
</Form>
: '' }

This was not good enough.这还不够好。 It would still error out.它仍然会出错。 I had to place the ternary immediately on the field in order for it to work.我必须立即将三元放在场上以使其工作。

Doing this for every single field would be a pain in the ass, so putting it into a function first seems to work better.对每个领域都这样做会很痛苦,因此首先将其放入 function 似乎效果更好。

Probably, you are trying to achieve data's populates when data didn't set yet.可能,您正在尝试在数据尚未设置时实现数据填充。 Need to be sure data is set already.需要确保数据已经设置。

You can use it like;你可以像这样使用它;

booking.assignedUser && console.log(booking.assignedUser.first) booking.assignedUser && console.log(booking.assignedUser.first)

If the page can't view components due to data is empty, need to use this condition beginning of view component.如果页面因数据为空而无法查看组件,则需要使用此条件开始查看组件。

data.length > 0 &&...</Component/> data.length > 0 &&...</Component/>

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

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