getstaticprops cannot use params from getstaticpaths in case of dynamic routing? MongoDB

251 views Asked by At

I am making a webpage which fetches data from mongoDB( atlas BASIC free plan) and has dynamic routing page with SSG. The dynamic routing page, [cogid].js, has getstaticpaths and getstaticprops. getstaticpaths seems work, but getstaticprops does not work. I guess the problem is variable "params.cogid" inside getstaticprops...

import { MongoClient } from "mongodb";
const { MONGODB_URI, MONGODB_DB } = process.env;

export default function Cog({ cogData }) {
  return (
      <div className="container mx-auto px-2 my-5 flex flex-col ">
          <p>COG ID: COG{cogData.cog_id}</p>
          <p>name: {cogData.name}</p>
      </div>
  );
}

export async function getStaticPaths() {
  const client = new MongoClient(MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  if (!client.isConnected()) await client.connect();
  const res = await client
    .db(MONGODB_DB)
    .collection("test1")
    .find({})
    .project({ cog_id: 1, _id: 0 })
    .toArray();

  if (client.isConnected()) client.close();

  const paths = res.map((copiedCog) => ({
    params: { cogid: copiedCog.cog_id },
  }));
  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  const client = new MongoClient(MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });

  if (!client.isConnected()) await client.connect();
  const resp = await client
    .db(MONGODB_DB)
    .collection("test1")
    .findOne({ cog_id: params.cogid });
  if (client.isConnected()) client.close();

  const cogData = await JSON.parse(JSON.stringify(resp));
  return { props: { cogData } };
}
1

There are 1 answers

0
matskohe On

I solved the problem. I should have changed the data type of params.cogid to Integer (from String?) like Number(params.cogid) or parseInt(params.cogid). It is because the type of the field "cog_id" of the DB is Integer.