Fetching All Products
getServerSideProps
getServerSideProps
(opens in a new tab) function is specific to server-side rendering (SSR).
It allows us to fetch data on the server before rendering the components .
It makes sure that the data is available at the time the page is requested by the client.
API.js
async function getServerSideProps() {
await db.connect();
const products = await Product.find().lean();
return {
props: {
products: products.map(db.convertDocOptToObj),
},
};
}
After connecting to Database
L3. retrieves a list of products using the Product model (From models file)
Product.find()
(opens in a new tab) is used to retrieve a list of documents from the "Product" collection in my database.lean()
(opens in a new tab) method is used to convert Mongoose documents into plain JavaScript objects
lean is doing the convertion but i still need to convert id , createdAt and updatedAt properties in my product model
db.convertDocOptToObj
converts the left properties to plain JavaScript objects and returns products as props to make it available to the component that's being rendered
db.js
function convertDocOptToObj(doc) {
doc._id = doc._id.toString();
doc.createdAt = doc.createdAt.toString();
doc.updatedAt = doc.updatedAt.toString();
return doc;
}