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

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

相关推荐
看到请催我学习13 分钟前
如何实现两个标签页之间的通信
javascript·css·typescript·node.js·html5
zqx_73 小时前
随记 前端框架React的初步认识
前端·react.js·前端框架
NiNg_1_2344 小时前
npm、yarn、pnpm之间的区别
前端·npm·node.js
余生H5 小时前
前端的全栈混合之路Meteor篇:关于前后端分离及与各框架的对比
前端·javascript·node.js·全栈
Ink6 小时前
从底层看 path.resolve 实现
前端·node.js
fishmemory7sec6 小时前
Koa2项目实战2(路由管理、项目结构优化)
数据库·mongodb·koa
奔跑吧邓邓子8 小时前
npm包管理深度探索:从基础到进阶全面教程!
前端·npm·node.js
缘友一世11 小时前
macos安装mongodb
数据库·mongodb·macos
知否技术20 小时前
为什么nodejs成为后端开发者的新宠?
前端·后端·node.js