简体   繁体   English

尝试从组件中访问 _id 道具。 Next.js、Mongodb、Mongoose

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

I am still brand new to mongodb and mongoose.我对 mongodb 和 mongoose 仍然是全新的。 I am trying to access the id property (_id) with demo._id after first using getServerSideProps.在第一次使用 getServerSideProps 之后,我尝试使用 demo._id 访问 id 属性(_id)。 It seems to be working from my page here at pages/demo.js它似乎在我的页面 pages/demo.js 上工作

pages/demos.js页面/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.我一直在努力从我的 API 处理程序函数中以及从我的组件中访问相同的 _id 属性,我不确定我在哪里搞砸了。 Below is an example:下面是一个例子:

components/NavItem.js组件/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这是 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. getServerSideProps不适用于非页面组件。 It is only worked in page files.它仅适用于页面文件。 In the components/NavItem.js getServerSideProps was never called so props.demos was undefinedcomponents/NavItem.js中,从未调用过getServerSideProps ,因此undefined props.demos

You have to call getServerSideProps in a page component and pass it to the component with prop drilling.您必须在页面组件中调用getServerSideProps并将其传递给带有道具钻孔的组件。

Also you should be guarding your app.此外,您应该保护您的应用程序。 use .map if "demos" exist如果“演示”存在,请使用.map

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

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

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