Here’s a simple working example:
import { MongoClient } from 'mongodb'
const uri = 'mongodb://localhost:27017'
const client = new MongoClient(uri)
async function data(collection: string, database: string = 'default') {
await client.connect()
return client.db(database).collection(collection)
}
const resolvers = {
Query: {
example: async () => {
const cursor = (await data('example'))
.find()
.toArray()
.finally(() => client.close())
return cursor
}
}
}
Is this the proper way to connect to MongoDB? Is this the correct way to close a connection, and is it required? Is this the most optimal way to use MongoDB; if not, how can this be done suitably?
The “Resolver” is a GraphQL resolver.