Next14 app +Vercel 集成 MongoDB

首先需要阅读集成文档 www.mongodb.com/developer/p.... 该文档是将从零集成(从创建账号到创建储存库)

当你到达这一步的时候,你的 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

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

相关推荐
十盒半价22 分钟前
深入理解 React useEffect:从基础到实战的全攻略
前端·react.js·trae
海底火旺26 分钟前
以一个简单的React应用理解数据绑定的重要性
前端·css·react.js
爱学习的茄子28 分钟前
React Hooks驱动的Todo应用:现代函数式组件开发实践与组件化架构深度解析
前端·react.js·面试
宇宙全栈Link28 分钟前
当 React 组件调用自定义 hooks,hooks 又调用其他 hooks 时,状态变化如何传播?
前端·javascript·react.js
归于尽30 分钟前
原生JS与React的事件差异
前端·javascript·react.js
伍哥的传说2 小时前
H3初识——入门介绍之常用中间件
前端·javascript·react.js·中间件·前端框架·node.js·ecmascript
超级土豆粉2 小时前
npm 包 scheduler 介绍
前端·npm·node.js
G等你下课3 小时前
React 事件机制原理
前端·react.js
遂心_3 小时前
深入剖析React待办事项应用:Hooks、组件化与性能优化实战
前端·react.js·前端框架
WildBlue3 小时前
流式输出:前端工程师的魔术表演,小白也能看懂!🎩✨
前端·javascript·node.js