You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt 3中对应Next.js getServerSideProps(基于MongoDB驱动)的等效实现问询

Nuxt 3中对应Next.js getServerSideProps(基于MongoDB驱动)的等效实现问询

What is the Nuxt 3 equivalent way to translate this Next.js page into a Nuxt page?

export const getServerSideProps: GetServerSideProps<PageProps> = async (
  context
) => {
  context.res.setHeader("Cache-Control", "no-store");

  const uri = process.env.MONGODB_URI as string;
  const client = new MongoClient(uri);

  await client.connect();
  const db = client.db("e-commerce");
  const collection = db.collection<Product>("products");
  const products = await collection.find({}).limit(10).toArray();
  await client.close();

  return {
    props: {
      products,
    },
  };
};

const ProductsPage: NextPage<PageProps> = ({ products }) => {
  return <ProductsSlider title="Suggested products" products={products} />;
};

export default ProductsPage;

Please assume that using the mongodb driver (instead of mongoose, for example), creating and closing a client for each request, and setting "Cache-Control" -> "no-store" is necessary for this use case.

One way would be to use the mongodb driver in a Nuxt API route and fetch the data from the API with useFetch on the page, but this does not "represent" the Next implementation, because by using a Nuxt API route there would be an additional round trip to the API route to fetch the data.
This does not happen in the Next.js page, as the data is fetched directly in getServerSideProps when the request hits the server.

Is there a way to do this in Nuxt using the mongodb driver, opening and closing the connection to the mongodb cluster during each request?

备注:内容来源于stack exchange,提问作者Tommy D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 12:29:52