我是 next.js 的新手。在以下代碼中,我在服務器上呈現主頁并通過名為“products.json”的檔案填充道具物件。我已經成功地做到了。現在我的下一步是getStaticProps通過 MongoDB 在名為 的函式中填充 props 物件。
我可以使用 MONGOOSE 連接到我的 MongoDB 嗎?如果沒有,請用最好的方法指導我。
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;
uj5u.com熱心網友回復:
您可以撰寫一個seed.js 檔案來填充,但我認為您希望在構建期間以自動化方式運行。
// 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",
},
};
}
我不知道這是什么用例,但效率不高。因為在開發環境中,getStaticProps隨著每個請求運行,它的行為就像getServerSideProps. 每次重繪 頁面時,都會執行此函式,您將向資料庫發送查詢以洗掉和寫入。這將導致網路延遲。Bether 方法是將上述函式寫入一個檔案中,該檔案seed.js位于某個級別,package.json然后node seed.js從終端運行
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504146.html
上一篇:PUT請求的適當HTTP錯誤代碼
