关于next.js:Next14-app-Vercel-集成-MongoDB

39次阅读

共计 2262 个字符,预计需要花费 6 分钟才能阅读完成。

首先须要浏览集成文档 https://www.mongodb.com/developer/products/atlas/how-to-conne… 该文档是将从零集成(从创立账号到创立储存库)

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

    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;
    
  3. src/app/api/db/[collection] 文件夹中新建 route.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};
    

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

  4. 发动申请,在你的任意 page.tsx 或者 layout.tsx 文件中应用 fetch 申请接口。能够看到我这里是有一个 test 数据库和 users 汇合,那么我的申请就是 fetch('/api/db/users')

    fetch('/api/db/[这里填入你的汇合名称]')

材料

数据库操作: 文档

分割:1612565136@qq.com

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

正文完
 0