Exporting A Single Instance of Existing Mongodb in Node

Thanks @JoeKarlsson!

Im actually in two separate repos. One is a Meteor app. That has the MongoDB that I need to access in my other repo, which is a simple create-react-app with Node/Express. I did come up with this in order to read/write that Mongo instance from Meteor in the other node app.

const { MongoClient } = require("mongodb")
const uri = "the local instance of my mongodb from meteo"

let client = new MongoClient(uri, { useUnifiedTopology: true })

module.exports = client

And then in another file where I’m wanting to use those operations:

require("dotenv").config({ path: "../.env" })
const client = require("./getMongo")

const test = async () => {
  await client.connect()
  const users = client.db("meteor").collection("users")
  const one = await users.findOne()
  console.log(one)
}

test()

This works and I think will allow me to do read/write operations from other files. What do you think about this approach @JoeKarlsson?

1 Like