如何在 NextJS 启动时初始化 Mongodb

发布于 2025-01-10 16:00:24 字数 788 浏览 2 评论 0原文

如您所知,NextJS 是 Jamstack 框架,我正在从 Node/express 迁移到它,但我的问题是如何在服务器启动时将服务器连接到数据库,就像我在 Express 中所做的那样? 现在可以在 NextJS 中放置我的初始化代码吗?我说的对吗? 我看到了一些代码,但有一些我不熟悉的打字稿代码

另一方面,我可以在服务器端函数上执行此操作,例如 getStaticProps 或 getServerSideProps这是我的代码 dbinit.js

import mongoose from "mongoose";
export const dbStatus = () => mongoose.connection.readyState;
export default function dbConnect() {
  if (dbStatus == 1) return "database is connected";
  mongoose.connect(
    `mongodb://localhost:${process.env.DBPORT}/${process.env.DBNAME}`
  );
}

index.js

export async function getServerSideProps() {
  const result = await dbConnect();
  console.log(dbStatus());
  return {
    props: {},
  };
}

使用此代码我能够连接到 mongodb,但存在一些问题,最重要的是我的代码不是干净的代码

As you know NextJS is Jamstack framework and I'm migrating from node/express to it but my problem is how to connect server to database at startup of server as i did in express?
there is now where to put my initalizing code in NextJS? Am I saying correct?
I saw some code to to that but there were typescript codes that im not familiar with them

On the other hand i'm able to do that on serverside functions like getStaticProps or getServerSideProps this is my code
dbinit.js

import mongoose from "mongoose";
export const dbStatus = () => mongoose.connection.readyState;
export default function dbConnect() {
  if (dbStatus == 1) return "database is connected";
  mongoose.connect(
    `mongodb://localhost:${process.env.DBPORT}/${process.env.DBNAME}`
  );
}

index.js

export async function getServerSideProps() {
  const result = await dbConnect();
  console.log(dbStatus());
  return {
    props: {},
  };
}

with this code im able to connect to mongodb but there are some problems and the most important is that mycode isnot cleancode

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寒冷纷飞旳雪 2025-01-17 16:00:24

在NextJS中,我们可以连接MongoDB作为中间件。这与 Express 中间件方法非常相似,如下所示。

// middleware/database.js

import { MongoClient } from 'mongodb';
import nextConnect from 'next-connect';

const client = new MongoClient('{YOUR-MONGODB-CONNECTION-STRING}', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function database(req, res, next) {
  if (!client.isConnected()) await client.connect();
  req.dbClient = client;
  req.db = client.db('MCT');
  return next();
}

const middleware = nextConnect();

middleware.use(database);

export default middleware;

更多详情,可以参考这个官方的 how-to doc 获取分步指导。 这里是使用的示例存储库。

In NextJS, we can connect MongoDB as middleware. This is very similar to the Express middleware approach as shown below.

// middleware/database.js

import { MongoClient } from 'mongodb';
import nextConnect from 'next-connect';

const client = new MongoClient('{YOUR-MONGODB-CONNECTION-STRING}', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function database(req, res, next) {
  if (!client.isConnected()) await client.connect();
  req.dbClient = client;
  req.db = client.db('MCT');
  return next();
}

const middleware = nextConnect();

middleware.use(database);

export default middleware;

For more details, you can refer to this official how-to doc for step-by-step guidance. Here is the example repository used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文