How can I create a simple Next.js API route that fetches data from my MongoDB collection?

clock icon

asked 386 days ago

message icon

1

eye icon

57

I’m new to Next.js API routes and MongoDB—what’s the minimal setup to connect, query one collection, and return JSON?

1 Answer

here's how you can do it:

1// pages/api/items.js
2import { MongoClient } from 'mongodb';
3
4const uri = process.env.MONGODB_URI;
5let client;
6
7async function getClient() {
8 if (!client) {
9 client = await MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
10 }
11 return client;
12}
13
14export default async function handler(req, res) {
15 const dbClient = await getClient();
16 const db = dbClient.db('myDatabase');
17 const items = await db.collection('items').find({}).toArray();
18 res.status(200).json(items);
19}
20
1// pages/api/items.js
2import { MongoClient } from 'mongodb';
3
4const uri = process.env.MONGODB_URI;
5let client;
6
7async function getClient() {
8 if (!client) {
9 client = await MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
10 }
11 return client;
12}
13
14export default async function handler(req, res) {
15 const dbClient = await getClient();
16 const db = dbClient.db('myDatabase');
17 const items = await db.collection('items').find({}).toArray();
18 res.status(200).json(items);
19}
20
  • Use process.env.MONGODB_URI for the connection string.
  • Call find({}).toArray() to get all documents and return as JSON.

1

Write your answer here

Top Questions