简体   繁体   English

如何在 getStaticProps 函数(next.js)中连接到 mongodb?

[英]How can I connect to mongodb in getStaticProps function(next.js)?

I'm new to next.js.我是 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".在以下代码中,我在服务器上呈现主页并通过名为“products.json”的文件填充道具 object。 I have successfully done that.我已经成功地做到了。 now the next step for me is to populate the props object, in the function named getStaticProps , through MongoDB.现在我的下一步是通过 MongoDB 在名为getStaticProps的 function 中填充道具 object。

CAN I CONNECT TO MY MongoDB USING MONGOOSE?我可以使用 MONGOOSE 连接到我的 MongoDB 吗? 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;

You could either write a seed.js file to populate but I thing you want to run in automated fashion during build time.您可以编写一个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",
    },

 };
}

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 .因为在开发环境中, getStaticProps与每个请求一起运行,它的作用类似于getServerSideProps every time you refresh your page, this function will be executed and you will send queries to the database to delete and write.每次你刷新你的页面,这个 function 将被执行,你将向数据库发送查询以删除和写入。 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 Bether 方法是将上述 function 写入文件中, seed.js位于package.json的某个级别,然后从终端运行node seed.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM