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/[这里填入你的集合名称]')

资料

数据库操作: 文档

联系:1612565136@qq.com

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

相关推荐
天意pt43 分钟前
Blog-SSR 系统操作手册(v1.0.0)
前端·vue.js·redis·mysql·docker·node.js·express
程序员iteng3 小时前
AI一键图表生成、样式修改的绘图开源工具【easy-draw】
spring boot·开源·node.js
2301_818732066 小时前
安装了node,但是cmd找不到node和npm,idea项目也运行失败 已解决
前端·npm·node.js
Benny的老巢9 小时前
【n8n工作流入门02】macOS安装n8n保姆级教程:Homebrew与npm两种方式详解
macos·npm·node.js·n8n·n8n工作流·homwbrew·n8n安装
2301_8187320610 小时前
下载nvm后,通过nvm无法下载node,有文件夹但是为空 全局cmd,查不到node和npm 已解决
前端·npm·node.js
亮子AI11 小时前
【MySQL】node.js 如何判断连接池是否正确连接上了?
数据库·mysql·node.js
a程序小傲11 小时前
【Node】单线程的Node.js为什么可以实现多线程?
java·数据库·后端·面试·node.js
程序员爱钓鱼1 天前
Node.js 编程实战:测试与调试 —— Mocha / Jest / Supertest 使用指南
前端·后端·node.js
冴羽1 天前
JavaScript Date 语法要过时了!以后用这个替代!
前端·javascript·node.js
张洪权1 天前
node fs 模块核心 api
node.js