'NextJS fetching nested array of objects from MongoDB using mongoose and getServerSideProps
I'm trying to fetch an array of objects from MongoDB, using mongoose and SSP. One hitch is that all ObjectIds must be converted into strings. Currently I'm doing it like this:
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
}
}
}
}
This produces: Error: If(...): Nothing was returned from render. I can fetch user without properties, no propblem, and I can console log the attached properties even though nothing is returned. What's happening here?
Solution 1:[1]
In order to send an array from getServerSideProps(), you should first transform it to a series of bytes with JSON.stringify, remember that HTTP sends text only. Re-transform as an array of objects in your React component with JSON.parse, with this method, you don't need to create the strings manually.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bguiz |
