First, create utils/mongodb.js
, we will use this to connect to MongoDB.
import { MongoClient } from 'mongodb';
export const connectToDatabase = async () => {
const uri = process.env.MONGODB_URI;
const dbName = process.env.MONGODB_DB;
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
// Access the specified database
const db = client.db(dbName);
return { client, db };
} catch (error) {
console.error('Failed to connect to MongoDB', error);
throw error;
}
};
then create a Server-Side API Endpoint server/api/products.js
import { connectToDatabase } from '../../utils/mongodb';
export default defineEventHandler(async () => {
const { client, db } = await connectToDatabase();
event.node.res.setHeader('Cache-Control', 'no-store');
try {
const collection = db.collection('products');
const products = await collection.find({}).limit(10).toArray();
return { products };
} catch (error) {
console.error('Failed to fetch products:', error);
throw createError({
statusCode: 500,
statusMessage: 'Failed to fetch products',
});
} finally {
await client.close();
}
});
then Fetch Data in the Nuxt Page Using useFetch
<template>
<div class="container mx-auto">
{{ products }}
</div>
</template>
<script setup>
const { data: products, error } = await useFetch('/api/products')
if (error.value) {
console.error(error.value)
}
</script>