Yeats
Yeats

Reputation: 2065

How to connect to mongodb database using Nextjs?

Trying to connect to my mongodb database in the latest version of Nextjs. Things have changed so much, so I don't longer know what to do.

There's an example of how to set up the connection here: https://github.com/vercel/next.js/tree/canary/examples/with-mongodb

They use this file:

//The mongodb.js file from the example
import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI
const options = {}

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

However, they forgot to add how to actually use it. I can't even begin to figure it out.

//pages/api/user.js

import client from '/lib/mongodb.js'

export default async function handler(req, res) {
  //How do I connect here?
}

And two bonus questions:

Upvotes: 1

Views: 5947

Answers (1)

Shiva
Shiva

Reputation: 572

You can do like this:

const dbClient = await client;
const db = dbClient.db('db-name');
const collection = db.collection('collection-name');
// example to get a doc in collection
const doc = await collection.findOne({query:""}, {...options})

Upvotes: 2

Related Questions