how to fix connection issue between vercel and mongodb

Viewed 16

im having issues with deploying my site using vercel this is the error:

[GET] /api/menu/menuItems
00:06:56:04
2022-09-06T05:06:56.382Z    315e3b25-b88f-4c8a-8d50-a323d2fd2b26    ERROR   MongoParseError: Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"
    at new ConnectionString (/var/task/node_modules/mongodb-connection-string-url/lib/index.js:86:19)
    at parseOptions (/var/task/node_modules/mongodb/lib/connection_string.js:213:17)
    at new MongoClient (/var/task/node_modules/mongodb/lib/mongo_client.js:62:63)
    at Object.9590 (/var/task/.next/server/pages/api/menu/menuItems.js:35:14)
    at __webpack_require__ (/var/task/.next/server/webpack-api-runtime.js:25:42)
    at __webpack_exec__ (/var/task/.next/server/pages/api/menu/menuItems.js:63:39)
    at /var/task/.next/server/pages/api/menu/menuItems.js:64:28
    at Object.<anonymous> (/var/task/.next/server/pages/api/menu/menuItems.js:67:3)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
RequestId: 315e3b25-b88f-4c8a-8d50-a323d2fd2b26 Error: Runtime exited with error: exit status 1
Runtime.ExitError

I have the env variable added to my vercel project already the same as the local one but when I deploy my app it'll load the app but none of the data comes through. it seems to not be able to make the api call for some reason I cant figure it out. I even tried adding the env variable with cli and still didn't work

mongodb.js

 import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI
const options = {
  useUnifiedTopology: true,
   useNewUrlParser: true,
  }


let client
let clientPromise

if (!process.env.MONGODB_URI) {
  throw new Error('Please add your Mongo URI to .env.local')
}

if (process.env.NODE_ENV === 'development') {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  // In production mode, it's best to not use a global variable.
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise

/api/menu/menuItems.js

import clientPromise from "../../../mongodb";

export default async function handler(req, res) {
  const client = await clientPromise;
  const db = client.db("RESTAURANT");

      const menu = await db.collection("menuItems").find({}).toArray();
      res.json({ status: 200, data: menu });
}

/pages/index.js

import Head from 'next/head'
import Image from 'next/image'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import mainImg from '../public/burrito.jpg'
import salsaImg from '../public/salsa.jpg'
import inteiorImg from '../public/place.jpg'
import styles from '../styles/Home.module.css'
import {motion} from 'framer-motion'
import Button from '@mui/material/Button'
import Card from '../components/specialsCard'


export default function Home({}) {
  const [menuItems, setMenuItems] = useState([]);

  console.log(process.env.MONGODB_URI)

  useEffect(() => {
    (async () => {
      const res = await fetch("/api/menu/menuItems");
      const menuItems = await res.json();
      setMenuItems(menuItems);
    })()
  }, [])

  return (
    <div style={{ width: '100%'}}>
      <Head>
        <title>Mexican restaurant</title>
        <meta name='keywords' content='restaurant, mexican, mexican food'/>
      </Head>
      <div className={styles.header}>
          <Image className={styles.img} src={mainImg} layout='fill' alt='mainImage'/>
              <motion.div className={styles.overlay} initial='hidden' animate='visible' variants={{
                hidden: {
                  scale: .8,
                  opacity: 0
                },
                visible: {
                  scale: 1,
                  opacity: 1,
                  transition: {
                    delay: .6
                  }
                }
              }}>
                <h3 style={{fontSize: '60px', margin:'0px',fontFamily: 'Hurricane, cursive'}}>Best Burritos In Town</h3>
                <p>burritos only made with organic and fresh ingredients</p>
              </motion.div>         
      </div>

      <div className={styles.salsaContainer}>
        <div className={styles.salsaContent}>
          <p style={{color: '#ff8d66', fontFamily: 'Hurricane, cursive',fontWeight: 'bold'}}>FREE CHIPS AND SALSA WITH EVERY ORDER</p>
          <h2 style={{marginTop: '2px'}}>TRY OUR INFAMOULSY SPICY SALSA. NO EXTRA CHARGE</h2>
          <p>Made with fresh tomotaos and spicy peppers. This salsa is known to leave customers happy and THIRSTY for more</p>
          <Button variant='contained' href='/menu' size='large' style={{backgroundColor: '#FFD966', marginTop: '20px'}}>Order Here</Button>
        </div>
        <div className={styles.salsaImg}>
          <Image src={salsaImg} alt='salsa'/>
        </div>
      </div>
      <div className={styles.subContainer}>
       <Image src={inteiorImg} alt='inteior'/>
       <div className={styles.interiorContent}>
           <h2 style={{fontFamily: 'Hurricane, cursive'}}>19th CENTURY DECOR</h2>
           <p>Come eat in and enjoy our welcoming aesthetics inspired by 19th century spanish design.</p>
       </div>
      </div>
      <div className={styles.subSpContainer}>
        <h2>popular menu items</h2>
        <div className={styles.subSpItems}>
          {(menuItems.data || []).map(item => {
            if(item.type === 'special'){
              return <Card title={item.title} 
                           description={item.description}
                           imgUrl={item.imgUrl}
                           id={item._id}
                           key={item._id}/>
            }
          })}
          <span style={{flexGrow:'2'}}><h2 style={{textAlign:'center'}}>Check these hot items and more!
                                                          <br/> <Link href='/menu'><a>See menu here</a></Link></h2></span>
        </div>
      </div>
    </div>
  )
}
0 Answers
Related