Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
How to create a module using mongoose for sharing a changing DB connection

i've been working on an app(Node.js with MongoDB using mongoose), and the server connects to 2 different databases, 1 generic containing username and password pairs for user authentication. Then, when the user signs in, I want to connect to a different database, named after the user's userId. I managed to create a module for sharing the generic UA database, but it's more difficult with the second one, since it doesn't open with the connection, but later on, when the user signs in. I guess i got inspired by the idea of react context kind of sharing.

So far i've got something like this

const mongoose = require("mongoose");

/* 
  UA = User Authentication
  US = User Specific
  DB = DataBase
*/

const UA_DB = mongoose.createConnection(/*...*/);
);
const User = UA_DB.model("User", require("../../data-schemas/user"));
let US_DB, Order, Item, Ingredient, Place;
console.log("opened UA database");

function sendUserId(newUserId) {
  userId = newUserId;
  US_DB = mongoose.createConnection(/*... ${newUserId} ...*/ );
  Order = US_DB.model("Order", require("../../data-schemas/order"));
  Item = US_DB.model("Item", require("../../data-schemas/item"));
  Ingredient = US_DB.model(
    "Ingredient",
    require("../../data-schemas/ingredient")
  );
  Place = US_DB.model("Place", require("../../data-schemas/place"));
  console.log("opened US database");
}

module.exports = {
  UA_DB: {
    User,
  },
  US_DB: {
    Order,
    Item,
    Ingredient,
    Place,
  },
  sendUserId,
};

Now, if I hadn't made it clear, the first, UA_DB works just fine, the user signs in just fine... When it comes to the US_DB i always get undefined as values(Cannot read property 'find' of undefined). I suspect the problem could be, that the exported value doesn't update with the value of the variables. Any ideas, how this could be solved?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Well, i figured it out. Instead of using precise values I use a function to return them, and to connect to the database.UserId is stored in a token, so after verification i check whether i am already connected to the right database (with the userId variable, which stores previous values) and then return curretn values of the models now my code looks something like this

const mongoose = require("mongoose");

/* 
  UA = User Authentication
  US = User Specific
  DB = DataBase
*/

const UA_DB = mongoose.createConnection(/* ... */
);
const User = UA_DB.model("User", require("../../data-schemas/user"));
let US_DB,
  Order,
  Item,
  Ingredient,
  Place = "some default value";
console.log("opened UA database");

let userId = "";

function getUS_DBModels(newUserId) {
  if (newUserId !== userId) {
    userId = newUserId;
    US_DB = mongoose.createConnection(`...${userId}...`
    );
    Order = US_DB.model("Order", require("../../data-schemas/order"));
    Item = US_DB.model("Item", require("../../data-schemas/item"));
    console.log("opened a US_DB connection");
    Ingredient = US_DB.model(
      "Ingredient",
      require("../../data-schemas/ingredient")
    );
    Place = US_DB.model("Place", require("../../data-schemas/place"));
  }
  return {
    Order, Item, Ingredient, Place
  }
}

module.exports = {
  UA_DB: {
    User,
  },
  getUS_DBModels,
};

For anyone wondering, in different modules you can access the values like this

const dbHandler = require("./path/to/the/module");
const { Item } = dbHandler.getUS_DBModels("UserId");
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda