Skip to content

Commit d77a0eb

Browse files
committed
✨ Update mongodb connection
1 parent b323c22 commit d77a0eb

File tree

6 files changed

+21
-41
lines changed

6 files changed

+21
-41
lines changed

README.md

+2-5
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,9 @@ You can use the following environment variables to modify the application's conf
6161

6262
Name|Default|Description
6363
--|--|--
64-
MONGODB_API|`null`|MongoDB Atlas API
65-
MONGODB_API_KEY|`null`|MongoDB Atlas API Key
66-
MONGODB_DATASOURCE|`null`|MongoDB Atlas DataSource
64+
MONGO_URI|`null`|MongoDB connection string
6765
NEXT_PUBLIC_GA_MEASUREMENT_ID|`null`|Google Analytics Measurement ID
68-
69-
Custom user data saved in `./data`, you can change them to yourself.
66+
NEXT_PUBLIC_ENABLE_REACT_SCAN|`false`|Enable to use [react-scan](https://react-scan.com/)
7067

7168
### ▼ Deployment
7269

app/api/mongo/find/route.ts

+5-15
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,11 @@
1+
import { connect } from "@/utils/mongo"
12
import { NextRequest, NextResponse } from "next/server"
23
import { WebResponse } from "../../../../utils/web"
34

45
export async function POST(request: NextRequest) {
56
const body = await request.json()
6-
const resp = await fetch(`${process.env.MONGODB_API}/action/find`, {
7-
method: 'POST',
8-
headers: {
9-
'Content-Type': 'application/json',
10-
'Access-Control-Request-Headers': '*',
11-
'api-key': process.env.MONGODB_API_KEY || '',
12-
},
13-
body: JSON.stringify({
14-
dataSource: process.env.MONGODB_DATASOURCE,
15-
...body,
16-
}),
17-
next: { revalidate: 0 },
18-
})
19-
const data = await resp.json()
20-
return NextResponse.json(WebResponse.successList(data.documents, data.documents.length >= body.limit))
7+
const mongo = await connect()
8+
const {database, collection, filter, ...options} = body
9+
const result = await mongo.db(database).collection(collection).find(filter, options).toArray()
10+
return NextResponse.json(WebResponse.successList(result, result.length >= body.limit))
2111
}

app/api/mongo/findOne/route.ts

-21
This file was deleted.

bun.lockb

4.27 KB
Binary file not shown.

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
"clsx": "^2.1.1",
2020
"cobe": "^0.6.3",
2121
"moment": "^2.30.1",
22+
"mongodb": "^6.11.0",
2223
"next": "^15.0.3",
2324
"next-view-transitions": "^0.3.4",
2425
"nextjs-google-analytics": "^2.3.7",

utils/mongo.ts

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { MongoClient } from 'mongodb'
2+
3+
let uri = process.env.MONGO_URI
4+
5+
let mongo: MongoClient | null = null
6+
7+
if (!uri) throw new Error('Missing environment variable MONGO_URI')
8+
9+
export async function connect() {
10+
if (mongo) return mongo
11+
mongo = await MongoClient.connect(uri as string)
12+
return mongo
13+
}

0 commit comments

Comments
 (0)