From the course: Next.js 14 from Scratch: Build a Real-World Project Using Next.js 14 and MongoDB
Unlock this course with a free trial
Join today to access over 25,200 courses taught by industry experts.
Database connection and Mongoose - Next.js Tutorial
From the course: Next.js 14 from Scratch: Build a Real-World Project Using Next.js 14 and MongoDB
Database connection and Mongoose
OK. So up to this point, you should have your database connected. You should have the data imported and the .env file with your MongoDB URI. So now what we're going to do is, in the root, create a folder called config. And this is going to be responsible, or this file here is going to be responsible for connecting to the database. So let's call this, we'll call this file db, I'll just call it database.js. All right, now we have to install the MongoDB driver itself, as well as Mongoose. So I'm going to go to another terminal here, and let's npm install mongodb and mongoose. And then in this file, we're going to import mongoose from mongoose. And let's initialize a variable here called connected. And we'll set that to false by default. Then we're going to create a function called connect DB. And this is going to be asynchronous, so we want to say async. Because when we work with the mongoose object, it's asynchronous. It returns a promise. Now, before we do anything to connect, there is…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
(Locked)
Create MongoDB database8m 44s
-
(Locked)
MongoDB Compass and importing data4m 36s
-
(Locked)
Database connection and Mongoose6m 31s
-
(Locked)
Your first API route6m 5s
-
(Locked)
Property and user models12m 30s
-
(Locked)
Fetch data using server component9m 48s
-
(Locked)
Requests file4m 25s
-
(Locked)
Fetch single property10m 51s
-
(Locked)
Single property page11m 54s
-
(Locked)
Property details component15m 34s
-
(Locked)
Spinner component2m 37s
-
(Locked)
-
-
-
-
-
-
-