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

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

相关推荐
知否技术3 小时前
为什么nodejs成为后端开发者的新宠?
前端·后端·node.js
攻城狮numberOne8 小时前
MongoDB集群模式详解及应用实战
数据库·mongodb
姜豆豆耶8 小时前
MongoDB-aggregate流式计算:带条件的关联查询使用案例分析
数据库·mongodb
DngYT8 小时前
MongoDB入门:安装及环境变量配置
数据库·mongodb
谢尔登8 小时前
【Node.js】worker_threads 多线程
node.js
osnet13 小时前
showdoc二次开发
node.js·vue
泯泷13 小时前
「生产必看」在企业环境中正确使用 Node.js 的九大原则
前端·后端·node.js
太阳火神的美丽人生14 小时前
Vant WeApp 开启 NPM 遇到的问题总结
前端·npm·node.js
bo_bo00116 小时前
MongoDB的使用
数据库·mongodb
卡布达ovo1 天前
MongoDB入门
数据库·mongodb