Next.js Discord

Discord Forum

Trying to connect the client to the database results in errors

Unanswered
Ocicat posted this in #help-forum
Open in Discord
OcicatOP
I've been struggling to connect the client to the database. Whenever I do, I seem to run into the error Module not found: Can't resolve 'child_process'. The page seems to try to re-render a bunch of times, but they won't actually connect.

How should I connect the client and database? And how do I get rid of the errors coming with it?

Error logs attached

11 Replies

OcicatOP
This is my code to connect the client with the database:
// mongodb client
import { MongoClient } from "mongodb";

if (!process.env.MONGODB_URI) {
  throw new Error('Missing environment variable: "MONGODB_URI"');
}

const uri = process.env.MONGODB_URI;
const options = { appName: "nouks-poezie" };

let _client: MongoClient;

if (process.env.NODE_ENV === "development") {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  const globalWithMongo = global as typeof globalThis & {
    _mongoClient?: MongoClient;
  };

  if (!globalWithMongo._mongoClient) {
    globalWithMongo._mongoClient = new MongoClient(uri, options);
  }
  _client = globalWithMongo._mongoClient;
} else {
  // In production mode, it's best to not use a global variable.
  _client = new MongoClient(uri, options);
}

// Export a module-scoped MongoClient. By doing this in a
// separate module, the client can be shared across functions.
const client = _client
export default client;
The request with the query
// query
import client from "@/database/connection/mongodbClient";
import VerzendType from "@/database/models/ProductType";

export default async function getProductTypes(amount = 10): Promise<VerzendType[]> {
  try {
    const db = client.db(process.env.DB_NAME);
    const productType = await db
      .collection(process.env.COL_PRODUCTS ?? "")
      .find({ type: "ProductType" })
      .limit(amount)
      .toArray();
    return JSON.parse(JSON.stringify(productType));
  } catch (e) {
    console.error(e);
    return [];
  }
}
The hook
// hook
import getProductTypes from "@/database/api/productType/getProductType";
import ProductType from "@/database/models/ProductType";
import { useEffect, useState } from "react";

export function useProductTypes() {
  const [productTypes, setProductTypes] = useState<ProductType[]>([]);
  useEffect(() => {
    const fetchProductTypes = async () => {
      try {
        const types = await getProductTypes();

        setProductTypes(types);
      } catch (e) {
        console.error(e);
      }
    };
    fetchProductTypes();
  }, []);
  return productTypes;
}
And the basic component:

// component
import Loading from "@/app/loading";
import { useProductTypes } from "@/hooks/useProductType";
import { MenuItem, Select } from "@mui/material";

export default function ProductTypeInput(props: {
  onChange?: (e: { target: { value: string } }) => void;
  value?: string;
}) {
  const handleChange = (e: { target: { value: string } }) => {
    if (props.onChange) props.onChange(e);
  };
  const productTypes = useProductTypes();
  console.log(productTypes);

  return productTypes ? (
    <Select
      labelId="ProductTypeInput"
      id="ProductTypeInput"
      value={props.value}
      onChange={handleChange}
      label="Product type"
    >
      <MenuItem value="">
        <em>None</em>
      </MenuItem>
      {productTypes.map((productType) => {
        const id = productType._id?.toString() ?? productType.verzending;
        return (
          <MenuItem value={id} key={id}>
            {productType._id?.toString()}
          </MenuItem>
        );
      })}
    </Select>
  ) : (
    <Loading />
  );
}
Sorry for all the code, I just really don't know where to look anymore
@Ocicat I've been struggling to connect the client to the database. Whenever I do, I seem to run into the error `Module not found: Can't resolve 'child_process'`. The page seems to try to re-render a bunch of times, but they won't actually connect. How should I connect the client and database? And how do I get rid of the errors coming with it? Error logs attached
What you are doing is wrong. Client could not and should not connect directly to the database. You here have 2 options:
1. Use server components to fetch the data on server and render accordingly
2. Use Route handlers to fetch the data client side and render(won't recommend)
OcicatOP
Alright, then I have a few questions:
- tanstack seems to call database requests from hooks, how does that work in this context?
- how should I be calling requests for the database then? I've been using requests from the serverside, but they don't actually update regularly, so the data I'm seeing becomes old quickly
@Ocicat Alright, then I have a few questions: - tanstack seems to call database requests from hooks, how does that work in this context? - how should I be calling requests for the database then? I've been using requests from the serverside, but they don't actually update regularly, so the data I'm seeing becomes old quickly
I haven't really looked into tanstack start but from what I've seen just from quick start docs, it uses something like useServerFn which idk how it works but what I can guess is it creates a setup similar to server actions and server actions are just normal api which you can use, same can be done with next as well.

If you want a similar setup, mark your file containing your db query with 'use server' and next will make it a server function which you can call in your hooks but this pattern is not recommended. You shouldn't use server actions to fetch data(though its possible to do that)
OcicatOP
Alright, thanks!
What would you recommend for the database requests? From the server side, but how do you make sure it sends the request again if the database is updated? (I couldn't get that to work, so that's why I tried the client side approach)
@Ocicat What would you recommend for the database requests? From the server side, but how do you make sure it sends the request again if the database is updated? (I couldn't get that to work, so that's why I tried the client side approach)
You can do 3 things:
- Do client side fetching and poll the requests, won't recommend
- Setup a websocket server, emit events when data change, client will react to those events, will recommend
- Periodically call router.refresh to refresh client components, won't recommend ever