In last post
- MongoDB was set up - able to store data from a form.
Redirecting to homepage after successful form submit.
Use useRouter
to do it:
- In
pages/new-note/index.js
import { useRouter } from 'next/router'
..
const router = useRouter(); // as usual, hook should be called first in react functional component
//after successful response of submit
router.replace("/"); // or push()
Getting data from mongoDB
- We could do it like, in page component GSP write a connection to our API route > that API route connects to mongoDB
i.e. page component GSP > nextjs api route > mongoDB
but its GSP and already serverside - so directly call DB from GSP.
page component GSP > mongoDB
because calling serverside route from serverside GSP is redundant.
Map the data on MongoDB because of _id field.
In pages\index.js
export async function getStaticProps() {
//fetch data from MongoDB
const uri = `mongodb+srv://${secret.user}:${secret.pass}@cluster0.xf7jy.mongodb.net/myFirstDB?retryWrites=true&w=majority`;
const dbName = "myFirstDB";
const coll = "notesColl2";
const client = new MongoClient(uri);
await client.connect();
console.log("Connected successfully to server!");
const db = client.db(dbName);
const notesCollection = db.collection(coll);
const notes = await notesCollection.find({}).toArray();
console.log("Found documents =>", notes);
client.close();
return {
props: {
notes: notes.map((item, index) => {
return {
id: item._id.toString(), //could do anything, e.g. index,
title: item.title,
image: item.image,
address: item.address,
description: item.description,
};
}),
},
};
}