How to Share MongoDB Connection Across Files

穿精又带淫゛_ 提交于 2021-01-25 20:50:41

问题


I'm trying to export the connection from mongoUtil.js to my server.js file, which worked. However, I'm also trying to export the variable collection through the function getDb() to another file where I handle a bunch of post requests, however, it says it's undefined. I've been racking my brain to understand what I'm doing incorrectly. What am I missing?

mongoUtil.js

const express = require('express');
const MongoClient = require('mongodb').MongoClient;


var collection;

module.exports = {
    connectToServer: function(callback){
        MongoClient.connect("<my connection string>", {
        useUnifiedTopology: true}, function (err, client){
            collection = client.db('mern-auth-2').collection('users');
//if I console.log collection here it works 
            
            return callback(err);
          
        });   
    },

    getDb: function() {
        return collection && console.log(collection);
//It says collection is undefined 
    }
};

来源:https://stackoverflow.com/questions/65556978/how-to-share-mongodb-connection-across-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!