I am tryin to fetch user data from MongoDB database using getServerSideProps with dynamic path. Here is my code.
import dbConnect from 'lib/dbConnect'
import User from 'models/User
export default function refID({user}){
return(
<>
<p>USERID:{user.userID}</p>
<p>USERNAME:{user.userName}</p>
</>
);
}
export async function getServerSideProps({ params }) {
await dbConnect()
const user = await User.findOne({userID}).lean()
user._id = user._id.toString()
return { props: { user } }
}
I have tried using hardcoded data.ie 'userID:S7L4SU'
which works fine except that for only that one user.
How can I define the userID such that it fetches data for that ID ?I have tried couple of methods which resulted to errors..
Sample path:http://localhost:3000/p/[userID]
How will i get around for dynamic path to work for all users in the DATABASE??Help here
CodePudding user response:
Try this:
export async function getServerSideProps(ctx) {
const { userID } = ctx.query;
await dbConnect()
const user = await User.findOne({userID}).lean()
user._id = user._id.toString()
return { props: { user } }
}