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

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…

Contents