【问题标题】:NextJS fetching nested array of objects from MongoDB using mongoose and getServerSidePropsNextJS 使用 mongoose 和 getServerSideProps 从 MongoDB 获取嵌套的对象数组
【发布时间】:2023-04-04 07:15:01
【问题描述】:

我正在尝试使用 mongoose 和 SSP 从 MongoDB 获取对象数组。一个问题是必须将所有 ObjectId 转换为字符串。目前我正在这样做:

export async function getServerSideProps({ query }) {
    
  try {
    const { user } = query
    await connectDB()
    const currentUser = await User.findOne({ user }).lean(),
      { _id } = await currentUser,
      userProperties = await Property.find({ ownerId: _id }).lean()
    
    currentUser._id = currentUser._id.toString()
        
    userProperties.forEach(props => {
      props._id = props._id.toString()
      props.ownerId = props.ownerId.toString()
      props.subarray.forEach(props => {
      props._id = props._id.toString()
    })
  })
        
  if (!currentUser) {
    return {
      notFound: true
      }
    }
    
    return {
      props: {
        currentUser,
        userProperties
      }
    }
  } catch (err) {
    console.log(err)
    
    return {
      redirect: {
        destination: '/',
        statusCode: 307
      }
    }
  }
}

这会产生:Error: If(...): Nothing was returned from render. 我可以获取没有属性的用户,没有问题,即使没有返回任何内容,我也可以控制台记录附加的属性。这里发生了什么?

【问题讨论】:

标签: javascript mongodb mongoose next.js server-side-rendering


【解决方案1】:

为了从getServerSideProps() 发送一个数组,您应该首先使用JSON.stringify 将其转换为一系列字节,记住HTTP 只发送文本。用JSON.parse在你的React组件中重新转换为一个对象数组,使用这种方法,你不需要手动创建字符串。

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 2021-08-13
    • 2015-01-31
    • 2021-05-17
    • 2017-06-26
    • 2018-06-22
    • 2019-03-28
    • 1970-01-01
    • 2019-09-11
    相关资源
    最近更新 更多