【问题标题】:NEXT.JS: Can't connect to mongoDB Database using getInitialPropsNEXT.JS:无法使用 getInitialProps 连接到 mongoDB 数据库
【发布时间】:2021-07-29 17:24:46
【问题描述】:

我正在尝试使用我的 _app.js 中的 getInitialProps 连接到我的示例 mongoDB 集合,但我遇到了 Module not found: Can't resolve 'dns' 这个问题

_app.js

import { connectToDatabase } from '../middlewares/mongodb';

function MyApp({ Component, pageProps, prop }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}

MyApp.getInitialProps = async (appContext) => {
  const { db } = await connectToDatabase();
  const data = await db
    .collection('listingsAndReviews')
    .find({})
    .limit(10)
    .toArray();

  const prop = JSON.parse(JSON.stringify(data));
  return { ...prop };
};

【问题讨论】:

    标签: node.js mongodb next.js


    【解决方案1】:

    getInitialProps 在初始页面加载期间在服务器上运行,在客户端导航期间在客户端上运行。因此getInitialProps 应该包含同构代码 - 能够在服务器和客户端环境中运行的代码。

    在您的情况下,您的代码需要 Node.js 环境(服务器),因此在浏览器上运行时会失败。


    一种可能的解决方案是将您的数据库获取逻辑移至 API 路由。

    // pages/api/listings
    
    export const fetchDbData = async () => {
        const { db } = await connectToDatabase();
        const data = await db
            .collection('listingsAndReviews')
            .find({})
            .limit(10)
            .toArray();
        return JSON.parse(JSON.stringify(data));
    }
    
    export default async (req, res) => {
        const data = await fetchDbData()
        res.status(200).json(data)
    }
    

    在您的getInitialProps 中,您可以在服务器上运行时直接调用fetchDbData 逻辑,或者在客户端上运行时进行 API 调用。

    import { fetchDbData } from './api/listings';
    
    MyApp.getInitialProps = async (appContext) => {
        let prop;
    
        if (appContext.ctx.req) { // Checks if running on server
            prop = await fetchDbData(); // Call logic directly on the server
        } else {
            const res = await fetch('/api/listings'); // Make API call on the client
            prop = await res.json();
        }
    
        return { ...prop };
    };
    

    这确保您的数据库获取逻辑将始终在服务器环境中运行。

    【讨论】:

    • 问题也出在我的中间件文件夹中的 MongoDB 连接上。如果我在 pages 文件夹内的根文件中导入连接,它会返回 DNS 错误。
    • 您只需要在您的 API 路由中导入即可。
    • 对不起,我忽略了它。但它现在工作了!再次感谢!
    • 您更新到 10.2 版了吗?如果是这样,它仍然有效吗?此外,您是否确认此“数据库查询”在每次页面加载/页面刷新时运行,换句话说,刷新页面,触发......再次刷新,触发?还是仅在整个应用程序的构建期间触发/运行?
    猜你喜欢
    • 2020-12-28
    • 2023-01-31
    • 2020-10-12
    • 2012-05-23
    • 1970-01-01
    • 2020-09-29
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多