Exporting A Single Instance of Existing Mongodb in Node

Hey there!

So my team has a meteor app that is using mongo. Right now, we make an API request to one of our other repos, do some stuff, and then hit that meteor app api to read/write the mongo data. We would like to read/write that data from the other repo instead of making an additional request. I would like to set this connection up as a singleton (functional programming rather than javascript classes). I’ve tried setting up the connection and exporting it to be used in other files to no avail. I’ve been able to connect, read/write within one file but not export that connection to be used by other files in Node. If anyone has any insight I would be super appreciative! Thanks so much!

1 Like

Hey @Austin_Burgard!

Thanks for making the leap to the MongoDB Community! We’re lucky to have you! :smiling_face_with_three_hearts:

Looks like you are trying to read/write data from two MongoDB databases within the same Meteor application so you don’t need to make multiple round trips to get data. It would helpful to see your code to better help you, but the short answer is yes, you can do this.

It is now possible to connect to remote/multiple databases with Meteor:

var database = new MongoInternals.RemoteCollectionDriver("<mongo url>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });

Where <mongo_url> is a MongoDB URL such as mongodb:// (with the database name)

If you don’t think that this solves your problem, would you be willing to share more of your code and error logs to help me further troubleshoot your connection issues? Thank you! :smiling_face_with_three_hearts:

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()


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

Yeah - that should work, but it might be a little complicated, but I think you understand the nuance and structure of your application more than I do :slight_smile: If it works, and you don’t have any major performance issues, I say it’s good to go. Nice job!!! :smiling_face_with_three_hearts: