skip to Main Content

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: {

    },
  };

};

2

Answers


  1. 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
      }
    };
    
    Login or Signup to reply.
  2. 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/…

    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 new 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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search