Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda