如何在NextJS的getServerSideProps中将数据库数据作为props传递。

huangapple go评论67阅读模式
英文:

How to pass database data as props in getServerSideProps in NextJS

问题

我想将从 MongoDB 数据库中提取的用户数据使用用户 ID 传递给返回部分的 props。如何将回调函数中的数据 docs 正确传递给 props

谢谢您的回复。

export const getServerSideProps = async (userid) => {
  await connectMongo();
  console.log("db connected on profile page");

  User.findOne({ id: userid }, function (err, docs) {
    if (err) {
      console.log(err);
    } else {
      console.log(docs.email);
    }
  });
  return {
    props: {

    },
  };
};
英文:

I want to pass the user data I fetched from a MongoDB database using the user id to the props in the return section. how can I send the data docs in the callback function to the props correctly?

Thanks for your response.

export const getServerSideProps = async (userid) => {
  await connectMongo();
  console.log("db connected on profile page");

  User.findOne({ id: userid }, function (err, docs) {
    if (err) {
      console.log(err);
    } else {
      console.log(docs.email);
    }
  });
  return {
    props: {

    },
  };

};

答案1

得分: 2

我在前端中使用了MongoDB,我已添加了一个代码片段,以提供一个完整的示例。然而,简而言之,您需要将DB查找请求的结果存储在一个变量中,如果您只是使用findOne()进行搜索或寻找一个结果,我建议将查找的结果存储在一个变量中,然后将其直接发送到页面作为一个prop。

但是,如果您从db.collection("submissions").find()请求中有多个结果,则需要调用JSON.parse(JSON.stringify(results))

客户端代码 /page/...

export async function getServerSideProps({req}) {
  let env = process.env.NODE_ENV === "development" ? "-dev" : "";

  const client = await clientPromise;
  const db = client.db('FormSubmissions' + env);
  const forwarded = req.headers['x-forwarded-for'];

  const ipAddress = typeof forwarded === 'string' ? forwarded.split(/, /)[0] : req.socket.remoteAddress;

  let _submissionsByIP = await db.collection("submissions").find({
    ipAddress: ipAddress,
  })

  let submissionsByIP = await _submissionsByIP.toArray();
  console.log('submissionsByIP',submissionsByIP);

  return {
    props: {
      submissionsByIP: JSON.parse(JSON.stringify(submissionsByIP)),
    },
  };
}

function Support_Sales({submissionsByIP}) {
  // ...
}

clientPromise

import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI
const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
}

let client
let clientPromise

if (!process.env.MONGODB_URI) {
  throw an Error('Invalid/Missing environment variable: "MONGODB_URI" - Add Mongo URI to .env.local')
}

if (process.env.NODE_ENV === 'development') {
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

export default clientPromise

希望这有助于您的项目。

英文:

I have used MongoDB in the frontend as well, I have added a snippet to give a full example. However simply put you'll need to store the result of the DB find request in a variable and if you're just searching with a findOne() or looking for one result I suggest storing the result of the find in a variable and sending it directly to the page as a prop.

However you will need to call JSON.parse(JSON.stringify(results)) if you have multiple results from a db.collection("submissions").find() request.

Client Side /page/...

<!-- begin snippet: js hide: true console: false babel: true -->

<!-- language: lang-js -->

export async function getServerSideProps({req}) {
  let env = process.env.NODE_ENV === &quot;development&quot; ? &quot;-dev&quot; : &quot;&quot;;

  const client = await clientPromise;
  const db = client.db(&#39;FormSubmissions&#39; + env);
  const forwarded = req.headers[&#39;x-forwarded-for&#39;];

  const ipAddress = typeof forwarded === &#39;string&#39; ? forwarded.split(/, /)[0] : req.socket.remoteAddress;

  let _submissionsByIP = await db.collection(&quot;submissions&quot;).find({
    ipAddress: ipAddress,
  })

  let submissionsByIP = await _submissionsByIP.toArray();
  console.log(&#39;submissionsByIP&#39;,submissionsByIP);

  return {
    props: {
      submissionsByIP: JSON.parse(JSON.stringify(submissionsByIP)),
    },
  };
}

function Support_Sales({submissionsByIP}) {
...
}

<!-- end snippet -->

clientPromise

<!-- begin snippet: js hide: true console: false babel: false -->

<!-- language: lang-js -->

import { MongoClient } from &#39;mongodb&#39;

const uri = process.env.MONGODB_URI
const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
}

let client
let clientPromise

if (!process.env.MONGODB_URI) {
  throw new Error(&#39;Invalid/Missing environment variable: &quot;MONGODB_URI&quot; - Add Mongo URI to .env.local&#39;)
}

if (process.env.NODE_ENV === &#39;development&#39;) {
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

export default clientPromise

<!-- end snippet -->

答案2

得分: 0

你可以创建一个新的变量来解决这个问题:

let userData = {};
User.findOne({ id: userid }, function (err, docs) {
  if (err) {
    console.log(err);
  } else {
    console.log(docs.email);
    userData = docs;
  }
});

return {
  props: {
    user: userData
  }
};

还有另一种方法,可以使用async,代码如下:

const userData = async User.findOne({ id: userid });

return {
  props: {
    user: userData
  }
};
英文:

you can create a new variable to solve the problem

let userData = {};
User.findOne({ id: userid }, function (err, docs) {
  if (err) {
    console.log(err);
  } else {
    console.log(docs.email);
    userData = docs
  }
});

return {
  props: {
    user: userData
  }
};

there is another solution by using async. the code be like:

const userData = async User.findOne({ id: userid });

return {
  props: {
    user: userData
  }
};

huangapple
  • 本文由 发表于 2023年2月27日 01:30:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定