I'm new to next.js. In the following code, I'm rendering the home page on the server and populating the props object through a file named "products.json". I have successfully done that. now the next step for me is to populate the props object, in the function named getStaticProps
, through MongoDB.
CAN I CONNECT TO MY MongoDB USING MONGOOSE? if not, please guide me with the best approach to do so.
import fs from "fs/promises";
import path from "path";
import Link from "next/link";
const Home = (props) => {
const { products } = props;
return (
<div>
<div>Lists of product:</div>
<ul>
{products.map((product) => {
return (
<li key={product.id}>
<Link href={`/${product.id}`}>{product.title}</Link>
</li>
);
})}
</ul>
</div>
);
};
export async function getStaticProps() {
console.log("Re-Generating...");
const filePath = path.join(process.cwd(), "data", "products.json");
const jsonData = await fs.readFile(filePath);
const data = JSON.parse(jsonData);
return {
props: data,
revalidate: 10,
};
}
export default Home;
CodePudding user response:
You could either write a seed.js
file to populate but I thing you want to run in automated fashion during build time.
// assuming that you already properly wrote this model. I anemd it Products
const Products = require("../models/products");
const mongoose = require("mongoose");
export async function getStaticProps() {
ongoose
.connect("mongodb://localhost:27017/products", {})
.catch((err) => console.log(err))
.then((con) => console.log("connected to db"));
// this data should match with Products schema
const products = require("/data/products.json");
const seedProducts = async () => {
try {
// if you dont delete you will have repeated data over and over
await Products.deleteMany();
await Products.insertMany(products);
// use this if you run a separate seeder.js file. otherwise your next.js app will exit
//process.exit();
} catch (error) {
console.log(error);
process.exit();
}
};
seedProducts();
// you always have to return something in this function
return {
props: {
something: "something",
},
};
}
I do not know what is the use case of this but it is not efficient. Because in a dev environment, getStaticProps
run with every request, it acts like getServerSideProps
. every time you refresh your page, this function will be executed and you will send queries to the database to delete and write. This will cause network latency. Bether way is write the above function in a file, seed.js
located in some level with package.json
and then run node seed.js
from the terminal