-3

I'm trying to make the connection with MongoDB database but I can't to export database object, inestead export a promise.

What I would be missing?

index.js

export const db = async() => { 
  return await MongoClient.connect(MONGO_URL)
}

I have also tried this way:

export const db = async() => { 
  const result = await MongoClient.connect(MONGO_URL)
  return result
}

resolvers.js

import { db } from '/mongodb'

This function returns Async Function db

  • I have also tried this way: `export const db = async() => { const result = await MongoClient.connect(MONGO_URL) return result }` – Alejandro Uray Dec 23 '18 at 13:42
  • `What I would be missing?` time. you can not return/export a value that does not exist (yet). That's what Promises are/are dealing with; a value that will be available at some point in the future, but not yet. – Thomas Dec 23 '18 at 13:56

2 Answers2

0

try this:

const db = async() => { 
  return await MongoClient.connect(MONGO_URL)
}

export const dbResult=db()

Then

import { dbResult} from './mongodb'
dbResult.then(res=>{
     //see what they are
     //console.log(dbResult,res)
})
xianshenglu
  • 4,943
  • 3
  • 17
  • 34
0

The reason is because you are exporting an async function (promise). What you could do is:

1) Change to require() over import (generally better, ES6 modules is iffy)

2) Do something like const database = await (require('./mongodb').db())

sausage
  • 101
  • 4