如何在 NextJS 启动时初始化 Mongodb
如您所知,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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在NextJS中,我们可以连接MongoDB作为中间件。这与 Express 中间件方法非常相似,如下所示。
更多详情,可以参考这个官方的 how-to doc 获取分步指导。 这里是使用的示例存储库。
In NextJS, we can connect MongoDB as middleware. This is very similar to the Express middleware approach as shown below.
For more details, you can refer to this official how-to doc for step-by-step guidance. Here is the example repository used.