api 폴더내에
lib/dbConnect.js
import mongoose from "mongoose";
const MONGODB_URI = process.env.DB_CONN_STR;
if (!MONGODB_URI) {
throw new Error(
"Please define the MONGODB_URI environment variable inside .env.local"
);
}
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
async function dbConnect() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
bufferCommands: false,
};
cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
return mongoose;
});
}
cached.conn = await cached.promise;
return cached.conn;
}
export default dbConnect;
해당 파일에서 (예를 들어, pages/index.tsx에서)
import Producta from "../src/components/Producta";
import Product from "../pages/api/models/product";
import dbConnect from "./api/middleware/dbConnect";
const Index = ({ products }: any) => (
<>
{/* Create a card for each pet */}
{products.map((product: any) => (
<div>{product.title}</div>
))}
</>
);
// both at request time and build time, preps the props passed to the UserProfile component.
export const getStaticProps = async () => {
await dbConnect();
const result = await Product.find({}, { createdAt: false, updatedAt: false });
console.log(result);
const products = result.map((doc) => {
const product = doc.toObject();
product._id = product._id.toString();
product.firstmeet = product.firstmeet.toString();
return product;
});
return {
props: { products: products },
};
};
export default Index;