Next14 app +Vercel 集成 MongoDB

首先需要阅读集成文档 https://www.mongodb.com/developer/products/atlas/how-to-connect-mongodb-atlas-to-vercel-using-the-new-integration. 该文档是将从零集成(从创建账号到创建储存库)

当你到达这一步的时候,你的 Vercel 中会有一个环境变量名称为 MONGODB_URI

这时候你也可以按照集成文档中 同步Vercel环境变量 进行同步,也可以直接将 MONGODB_URI变量复制到本地环境

当你做完这些后可以阅读 文档 ,该文档会教你 注意事项、以及与 Vercel 集成方法 (这个我们已经按照上面的步骤以及集成了则可以跳过)、以及在 Atlas UI 中 管理 Vercel 连接

这里是我的 Atlas UI 面板,可以看到左上角我有一个 next 的组织,然后有一个项目名称也叫 next 有一个库叫做 Cluster0,并且我的 next 项目是与 Vercel 相绑定,Vercel Projects 中我绑定了两个项目一个 yintan 一个 blasfin

你在你绑定的项目中 Database Access 菜单中可以看到有一个 vercel-admin-user-xxxxx,这是你集成 vercel 自动创建

前置步骤做完后进入代码中

正题

  1. 下载 mongodb 依赖包(如果没有的话)

  2. 新建 db.ts 文件,你可以在 src/server 或者 src/lib 创建。下面这段代码可以在 vercel 示例项目 中找到。请保证你的环境变量中有 MONGODB_URI

ts 复制代码
import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI as string; // your mongodb connection string
const options = {};

declare global {
  var _mongoClientPromise: Promise<MongoClient>;
}

class Singleton {
  private static _instance: Singleton;
  private client: MongoClient;
  private clientPromise: Promise<MongoClient>;
  private constructor() {
    this.client = new MongoClient(uri, options);
    this.clientPromise = this.client.connect();
    if (process.env.NODE_ENV === 'development') {
      // In development mode, use a global variable so that the value
      // is preserved across module reloads caused by HMR (Hot Module Replacement).
      global._mongoClientPromise = this.clientPromise;
    }
  }

  public static get instance() {
    if (!this._instance) {
      this._instance = new Singleton();
    }
    return this._instance.clientPromise;
  }
}
const clientPromise = Singleton.instance;

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;
  1. src/app/api/db/[collection] 文件夹中新建 route.ts 文件
ts 复制代码
import clientPromise from '@/lib/db';
import type { NextRequest } from 'next/server';

async function handler(
  req: NextRequest,
  { params }: { params: { collection: string } }
) {
  try {
    const client = await clientPromise;
    // test 替换成你的集合名称
    const collection = client.db('test').collection(params.collection);
    // 数据库操作方法
    const results = await collection.find({}).toArray();
    console.log('Found documents =>', results);
    return Response.json({ data: results });
  } catch (error) {
    console.log('error', error);

    // 在出错时发送适当的错误响应
    new Response('Hello, Next.js!', {
      status: 500,
    });
  }
}

export { handler as GET, handler as POST };

上面代码演示了如何操作数据库数据。

  1. 发起请求,在你的任意 page.tsx 或者 layout.tsx 文件中使用 fetch 请求接口。可以看到我这里是有一个 test 数据库和 users 集合,那么我的请求就是 fetch('/api/db/users')
ts 复制代码
fetch('/api/db/[这里填入你的集合名称]')

资料

数据库操作: 文档

联系:[email protected]

示例仓库:暂无(后续补上)

相关推荐
xd000023 小时前
11. vue pinia 和react redux、jotai对比
node.js
程序猿小D4 小时前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
前端老六喔12 小时前
🎉 开源项目推荐 | 让你的 TypeScript/React 项目瘦身更简单!
node.js·前端工程化
醉书生ꦿ℘゜এ12 小时前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
超级土豆粉13 小时前
从0到1写一个适用于Node.js的User Agent生成库
linux·ubuntu·node.js
空中湖16 小时前
‘pnpm‘ 不是内部或外部命令,也不是可运行的程序
npm·node.js
SailingCoder17 小时前
grafana-mcp-analyzer:基于 MCP 的轻量 AI 分析监控图表的运维神器!
运维·人工智能·typescript·node.js·grafana
又又呢20 小时前
前端面试题总结——webpack篇
前端·webpack·node.js
avoidaily1 天前
使用Node.js分片上传大文件到阿里云OSS
阿里云·node.js·云计算
xd000021 天前
8.axios Http网络请求库(1)
node.js