简体   繁体   English

将Mongodb数据库连接公开到Next.js 6应用程序中的页面

[英]Expose mongodb database connection to pages in Next.js 6 app

I am building an app with Next.js v6 , and I would like to fill pages with results from a local mongodb database. 我正在使用Next.js v6构建应用程序,我想用本地mongodb数据库的结果填充页面。

Ideally, I would like to do something as simple as this example from the tutorial , but instead of using an api fetch, just send a query to my mongodb on localhost. 理想情况下,我想做一些与本教程中的示例一样简单的事情,但是除了使用api fetch之外,只需向本地主机上的mongodb发送查询即可。

Example from Next.js tutorial Next.js教程中的示例

import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>
    <h1>Batman TV Shows</h1>
    <ul>
      {props.shows.map(({show}) => (
        <li key={show.id}>
          <Link as={`/p/${show.id}`} href={`/post?id=${show.id}`}>
            <a>{show.name}</a>
          </Link>
        </li>
      ))}
    </ul>
  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://api.tvmaze.com/search/shows?q=batman')
  const data = await res.json()

  console.log(`Show data fetched. Count: ${data.length}`)

  return {
    shows: data
  }
}

export default Index

My problem is in trying to get my database connected and exposed to the app so that I can do something like this on a page names resources.js: 我的问题是尝试使数据库连接并公开到应用程序,以便我可以在名为resources.js的页面上执行类似的操作:

import Layout from '../components/Layout'
import Link from 'next/link'

const Resources = (props) => {
    <Layout>
        <h3>Resources</h3>
        <ul style={listStyle}>
            {props.resources.map(({resource}) => (
                <li key={resource._id}>
                    <Link href={resource.link}>
                        <a>{resource.title}</a>
                    </Link>
                </li>
            ))}
        </ul>
    </Layout>
};

Resources.getInitialProps = async function() {  

    // get query from mongo DB
    // req is 'undefined' -- I want to see the db here
    const list = await req.db.get('resources').find();
    return list;

}

export default Resources;

But I don't know how I can expose the database in a function that could be accessed from pages anywhere in the app. 但是我不知道如何以可以从应用程序中任何位置的页面访问的功能公开数据库。 It seems that older tutorials of examples used something like server.use((req, res, next) => { req.db = dbToExpose }); 似乎旧的示例教程使用了诸如server.use((req, res, next) => { req.db = dbToExpose }); in the main index.js file, but this doesn't seem to be working with Next.js v. 6?? 在主要的index.js文件中,但这似乎不适用于Next.js v。6?

For example, this sample repo from this tutorial doesn't seem to work for me with the latest version of Next.js. 例如, 教程中的此示例存储库似乎不适用于最新版本的Next.js。 The db exposed trough req.db comes up as 'undefined' when you try to access it from aa page. 当您尝试从一个页面访问它时,暴露在数据库中的req.db槽显示为“未定义”。 But perhaps I am missing some other problem. 但是也许我错过了其他一些问题。

Here's my attempt in my base server file at exposing the db so I can access it from files in pages/ : 这是我在基本服务器文件中尝试公开的数据库,以便可以从pages/文件访问它:

const express = require('express')
const next = require('next')
const monk = require('monk')('localhost/myDatabase')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
.then(() => {
  const server = express()

  // This is not working to expose the db!
  server.use((req, res, next) => {
    req.db = monk
    next()
  });

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})

you should not expose any secure data or do database connecting in Nextjs pages. 您不应该在Nextjs页面中公开任何安全数据或进行数据库连接。 This post show the way for connect to database with NextJs without api 这篇文章展示了使用不带api的NextJs连接数据库的方法

You would need to wrap your Mongo DB in an API, which you could serve with the next server to avoid CORS issues. 您需要将您的Mongo数据库包装在一个API中,您可以将其与下一个服务器一起使用以避免CORS问题。 Next does not expose the Express request to the pages since this is not available on client rendering. Next不会将Express请求公开给页面,因为这在客户端渲染中不可用。

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

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