0

I'm new to MongoDB.

When I create my node.js server I use only one DB connection (on start I connect to it). But imagine: I have one database with some generic tables, and more databases - each for a custom client.

How can I create those DB at runtime?

start.js:

const mongoose = require("mongoose");

// import environmental variables from variables.env file
require("dotenv").config({ path: "variables.env" });

mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise;
mongoose.connection.on("error", err => {
  console.error(` → ${err.message}`);
});

require("./models/MaintenanceType");
require("./models/Maintenance");

const app = require("./app");
app.set("port", process.env.PORT || 7777);
const server = app.listen(app.get("port"), () => {
  console.log('started');
});

variables.env (example):

NODE_ENV=development
DATABASE=mongodb://db:qwe123@sometest.server.com:412345/webtest
PORT=1234
SECRET=webtest
KEY=webtestcom

and controller:

const mongoose = require("mongoose");
const Maintenance = mongoose.model("Maintenance");

exports.createMaintenance = async (req, res) => {
  const maintenance = await new Maintenance(req.body).save();
  // ALSO create a db and table if not exists for this client and use it somehow
  res.json(maintenance);
};

is it possible to do?

Acapulco
  • 3,373
  • 8
  • 38
  • 51
brabertaser19
  • 5,678
  • 16
  • 78
  • 184
  • Possible duplicate for https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project – Rashad Ibrahimov Oct 24 '18 at 21:01
  • @rashad nope, totally different – brabertaser19 Oct 25 '18 at 12:08
  • Could you please explain the difference? I see in both questions it's asked to have connections to different databases. And there are 2 ways to do this as I described in my answer. Did I misunderstand your question? – Rashad Ibrahimov Oct 25 '18 at 12:54
  • @rashad I have to use it as multi-tenancy schema – brabertaser19 Oct 25 '18 at 13:59
  • @rashad so db-s are dynamic. not a predifined project in a project like this: https://gist.github.com/alancasagrande/23e6284e24dadafce8c0 – brabertaser19 Oct 25 '18 at 14:00
  • Not sure I fully understand you. Isn't `useDb()` dynamic for you? ) You can get connection to another database and use it any time at any place in the code using `const dbCustom = db.useDb('newDb');`, and it's not predefined. – Rashad Ibrahimov Oct 25 '18 at 16:04

1 Answers1

0

You can create new connection

mongoose.connect('URI_FOR_ANOTHER_DATABASE')

But it's bad idea to create new connections, so the driver has a feature to use existing connections to query another database, for this purpose you can check useDb() method as shown here

Rashad Ibrahimov
  • 3,279
  • 2
  • 18
  • 39