Leveraging NextJS to retrieve a complex array of objects from MongoDB through the use of mongoose and getServerSide

My goal is to retrieve an array of objects from MongoDB, utilizing mongoose and SSP. The only challenge I am facing is that all ObjectIds need to be converted into strings. Currently, I am handling it in the following manner:

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 leads to:

Error: If(...): Nothing was returned from render.
I can fetch user without properties without an issue, and I can log the properties even though nothing is being returned. What could be the issue here?

Answer №1

To successfully pass an array from the getServerSideProps() function, you must convert it into a byte stream using JSON.stringify. Keep in mind that HTTP can only transmit text data. Upon receiving the data in your React component, convert it back into an array of objects using JSON.parse. This method eliminates the need to manually handle string conversions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Formik in React for automatic updates to a Material-UI TextField when blurred

Presently, I am developing a dynamic table where users can simultaneously modify multiple user details in bulk (Refer to the Image). The implementation involves utilizing Material-UI's <TextField/> component along with Formik for managing form s ...

Show JSON information from a jQuery post request

Greetings, I am currently working on implementing a login script using Ajax. My objective is to retrieve and display data such as email and username, and then store it in local storage. Although I can successfully obtain the data in JSON format, I want to ...

Safari's Web Audio API suffering from subpar performance and various shortcomings

For my University project, I am developing an HTML and JavaScript-based mp3 player using the Web Audio API. You can check out the progress of this project by visiting this link: While everything is running smoothly on Firefox and Chrome, Safari is posing ...

Changing HTML dynamically does not trigger the ng-click event within ng-bind-html

I have developed a custom directive that can display messages along with rendering HTML content that may contain Angular attributes like buttons, anchor tags with ng-click attribute, and more. index.html: <ir-error-panel status="status"></ir-err ...

When attempting to manage errors in mongoose.findOne, I am encountering the issue of receiving an 'Unhandled 'error' event'

Handling 'error' Events with Mongoose Attempting to handle errors in the mongoose.findOne() function led me to try using a second parameter in this manner: mongoose.findOne({ uuid: uuid }, (err,doc)). However, I encountered an issue where no err ...

Experiencing an issue with the countdown timer while utilizing react-countdown library

Currently, I am in the process of creating a countdown timer that allows users to input time in minutes and start or stop the clock. However, I have encountered two challenges: I defined a state running to determine if the clock is running, and based on t ...

The console correctly detects the value, but is unable to set the innerHTML property of null

I am currently working on a webpage that allows users to sign in and create an account. The issue I'm facing is that when I try to display the user's information, I encounter the error 'Cannot set property 'innerHTML' of null.&apos ...

What is the best way to omit a field from my query if the associated variable is empty?

I need help creating a dynamic MongoDB query function that can handle multiple field values, including cases where some fields may be empty strings. In these instances, I want MongoDB to disregard those parts of the query. Here is my current query functio ...

How can you pick the element that is nearest to the top of a window?

My goal is to have a fixed list of page sections on the side that highlights the link of the section you're currently viewing as you scroll through the page. This is the code I've come up with: $(document).scroll(function(){ $allSections = $(&a ...

Tips for running multiple JavaScript functions in ASP.NET using Button's OnClientClick property

Is there a way to execute multiple JavaScript functions in ASP.NET to perform various tasks such as inserting a desired text in a TextBox, changing the TextBox background color and font color, and disabling or locking a Button for a specific duration? I ha ...

A guide on implementing reverse routes using react-router

Is there a best practice for constructing URLs for links in my react-router based app? In the Zend Framework world of php, I would use a url helper that utilizes reverse routes. By providing the route name and parameters to a route configuration, it would ...

jQuery disregards the else-if statement

Currently, I am developing a web application that prompts the user to input an "application" by providing the StudentID and JobID. With the help of jQuery, I am able to notify the user if the student or job entered does not exist, if the application is alr ...

ExpressJS - Issue with POST Router resulting in 404 Error

I am currently getting acquainted with ExpressJS and am in the process of setting up a small todo list app while incorporating React. I have successfully retrieved my list of todos from a mysql database, however, I am encountering difficulties with the POS ...

Retrieve the number of records generated each month using Mongoose in Node.js

Here is my current schema for users in my application: // User schema const userSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, email: { type: String, unique: true, required: true, trim: ...

Issue encountered when attempting to sign up a user with passport.js

I encounter a "Bad Request" message when attempting to create a new user using Postman with the following content: { "username": "username", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="07626a666e6b47626a66 ...

Step-by-step guide on implementing a fade effect to a specific JavaScript element ID

When I click a button, the image on the screen disappears. I am looking to add a fade effect to this action. Can someone help me achieve this using CSS? #hide{-webkit-transition: all 1s ease-in-out;} For reference, here is a demo showcasing the current b ...

Duplicating an array retrieved through a jQuery ajax request

Currently, I am encountering an issue while attempting to duplicate a JSON array within this specific JavaScript function: var test = new array(); function showUser(user, pass, remember) { $.getJSON("login.php", { username : user, password : pass, che ...

Using jQuery to manipulate the image within a specific div element

I'm facing an issue with locating the img src within a div. I've written a function to find all the divs with specific ids: function identifyDiv(){ divArray = $("div[id^='your']"); divArray = _.shuffle(divArray); } This is the ...

Sending values from multiple radio groups in JavaScript can be done by accessing each group individually and extracting

This is an add to cart system. Currently, I am able to send quantity with an ID. However, I also want to send radio group values. How can I achieve this? Here are my codes: product.php <script> jQuery(function ($) { $('.popbutton').on(&a ...

Ways to stop React from refreshing the page upon clicking the submit button

Is it possible to prevent a React component from reloading the page when a submit button is pressed? Here is an example of component code: class MyComponent extends React.Component<IEditCampaignStateProps & IEditCampaignDispatchProps, EditCampaignStat ...