简体   繁体   中英

Trying to access _id prop from within a component. Next.js, Mongodb, Mongoose

I am still brand new to mongodb and mongoose. I am trying to access the id property (_id) with demo._id after first using getServerSideProps. It seems to be working from my page here at pages/demo.js

pages/demos.js

import React from 'react'
import Link from 'next/link';
import dbConnect from '../lib/dbConnect'
import Demo from '../models/Demo'
// import Layout from '../components/layout'

const DemosPage = ({ demos }) => {
  return (
    <>
      {/* <Layout> */}
        <div>
          {demos.map((demo) => (
            <div key={demo._id}>
              <div className="card">
                <img src={demo.image_url} />
                <div className="main-content">
                  <p className="text-gray-900"> {demo._id}</p>
                  <div className="btn-container">
                    <Link href="/demos/[id]/edit" as={`/demos/${demo._id}/edit`}>
                      <button className="btn edit">Edit</button>
                    </Link>
                    <Link href="/demos/[id]" as={`/demos/${demo._id}`}>
                      <button className="btn view">View</button>
                    </Link>
                  </div>
                </div>
              </div>
              
            </div>
          ))}
        </div>
      {/* </Layout> */}
    </>
  )
}

export async function getServerSideProps() {

  await dbConnect()
  
  const result = await Demo.find({})
  const demos = result.map((doc) => {
    const demo = doc.toObject()
    demo._id = demo._id.toString()
    return demo
  })

  return { props: { demos: demos } }
}

export default DemosPage

I have been struggling to access the same _id property from within my API handler functions and also from within my components, and I am not sure where I have been messing it up. Below is an example:

components/NavItem.js

import React from 'react'
import dbConnect from '../lib/dbConnect'
import Demo from '../models/Demo'
import Link from 'next/link'

const NavItem = ({ demos }) => {
  return (
    <span key={index} className='block -ml-1.5'>
      <div>
        {demos.map((demo) => (
          <Link key={demo._id} href="/demos/[id]" as={`/demos/${demo._id}`}>
            <a>{demo._id}</a>
          </Link>
        ))}
      </div>
    </span>
  )
}

export async function getServerSideProps() {

  await dbConnect()
  
  const result = await Demo.find({})
  const demos = result.map((doc) => {
    const demo = doc.toObject()
    demo._id = demo._id.toString()
    return demo
  })

  return { props: { demos: demos } }
}

export default NavItem


I am getting the following error

Server Error

TypeError: Cannot read properties of undefined (reading 'map')
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source

components/NavItem.js (10:15) @ NavItem

   8 | <span key={index} className='block -ml-1.5'>
   9 |   <div>
> 10 |     {demos.map((demo) => (
     |           ^
  11 |       <Link key={demo._id} href="/demos/[id]" as={`/demos/${demo._id}`}>
  12 |         <a>{demo._id}</a>
  13 |       </Link>

and here is the Model

import mongoose from 'mongoose'

const DemoSchema = new mongoose.Schema({
  demo_variable: {
    type: Object,
  },
  demo_name: {
    type: String,
  },
})

export default mongoose.models.Demo || mongoose.model('Demo', DemoSchema)

any help would be greatly appreciated. Thanks in advance...

getServerSideProps does not work on non-page components. It is only worked in page files. In the components/NavItem.js getServerSideProps was never called so props.demos was undefined

You have to call getServerSideProps in a page component and pass it to the component with prop drilling.

Also you should be guarding your app. use .map if "demos" exist

  {demos && demos.map((demo) => (

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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