~M•29
Published on

CS08 - Adding MongoDB

Authors
  • avatar
    Name
    MDolce
    Twitter
Table of Contents

Problems we need to solve:

Adding a MongoDB Atlas database using @vercel/postgres

Also, because of this error message:

Solution:

NOTE: Make sure to have a MongoDB Atlas account and database

  1. Import the project into a new GitHub repo
  2. Connect and deploy the project to an existing Vercel account
  3. Create a new MongoDB Atlas integration from integration tab on dashboard in Vercel
  4. If you are using Vercel CLI, verify that you have vercel installed
  5. If not, run npm install vercel from terminal to add vercel to package.json
  6. Run vercel from terminal then select a credential choice, to connect MongoDB Atlas project to Vercel deployment
  7. Run vercel env pull .env.local
  8. Run `cp .env.example .env or create new .env project file at root level directory
  9. Copy the MONGODB_URI connection string to .env mongodb+srv://<USERNAME>:<PASSWORD>@cluster0.tdm0q.mongodb.net/<DBNAME>?retryWrites=true&w=majority
  10. Update .gitignore and add .env

Creating the endpoint with MongoDB

tracks-js
import clientPromise from '@/lib/mogodb'

export default async (req, res) => {
   try {
       const client = await clientPromise;
       const db = client.db("ProjectIDX");

       const getTracks = await db
           .collection("tracks")
           .find({})
           .sort({ metacritic: -1 })
           .limit(10)
           .toArray();

       res.json(movies);
   } catch (e) {
       console.error(e);
   }
};

users-placeholder-data-js
const { db } = require('@vercel/postgres');
const {
 users,

Ref