Reputation: 2197
I am building an app with Next.js v6, and I would like to fill pages with results from a local mongodb database.
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.
Example from Next.js tutorial
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:
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 });
in the main index.js
file, but this doesn't seem to be working with 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. The db exposed trough req.db
comes up as 'undefined' when you try to access it from a a page. 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/
:
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)
})
Upvotes: 0
Views: 3663
Reputation: 437
you should not expose any secure data or do database connecting in Nextjs pages. This post show the way for connect to database with NextJs without api
Upvotes: 2
Reputation: 1652
You would need to wrap your Mongo DB in an API, which you could serve with the next server to avoid CORS issues. Next does not expose the Express request to the pages since this is not available on client rendering.
Upvotes: 1