问题
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