Mongo and Next.JS
In this tutorial, we will learn how to connect to MongoDB and use Next.JS to create a simple app.
Steps
Use
create-next-appto bootstrap a next appnpx create-next-app --example with-mongodb dabble-nextjs-mongoChange into the
dabble-nextjs-mongoproject directorycd dabble-nextjs-mongoRun the dev server
npm run devTry to view the app by visiting
localhost:3000- you should see an error because we still need to set the mongo connection stringRename
env.local.exampletoenv.localOpen
env.localand set the following environment variablesMONGODB_URI=your-mongodb-uri
MONGODB_DB=your-mongodbSetting up a mongodb on Atlas
- Go to MongoDB Atlas
- mongodb+srv://USERNAME:PASSWORD@cluster0.tdm0q.mongodb.net/DBNAME?retryWrites=true&w=majority
- Setup a username and password
- Set the network access for your IP address
Restart the dev server, this time there should not be an error and you will see a screen like the following.
Create a file named
pages/api/movies.jsand paste in the following code.import { connectToDatabase } from "../../util/mongodb";
export default async (req, res) => {
const { db } = await connectToDatabase();
const movies = await db
.collection("movies")
.find({})
.sort({ metacritic: -1 })
.limit(20)
.toArray();
res.json(movies);
};