Create a dedicated Database per user in a MEAN App

2019-08-24 03:48发布

I am working on a project that requires a dedicated database per registered user. I prefer working with MongoDB so I'm using that for the same (Am I Right?). The app uses a REST API as the backend (written in Node Express) and an AngularJS App. So, what I think of doing is whenever a user makes a request to some API endpoint say, a GET request to api/user/mydata, I would create a connection to his particular database, fetch the required data, close the connection and return the fetched data as the response. Is this approach correct? Also, I'm using Mongoose as the ODM and PassportJS for user Authentication. Moreover, users of my app are mutually exclusive. There is no data connection between a user with any other registered user.

1条回答
倾城 Initia
2楼-- · 2019-08-24 04:37

There's a way to do that but only without using Mongoose. You would have to create a root connection to your MongoDB server (mind it, not to a particular database on that server) using the mongodb node module and then you can switch between the database as per your query requirement without creating a new connection per database as shown below:

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

// URL to the root of MongoDB Server and not a particular db
const url = 'mongodb://localhost:27017';

// Database Names
const dbName1 = 'myproject1';
const dbName2 = 'myproject2';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db1 = client.db(dbName1);
  const db2 = client.db(dbName2);

  client.close();
});

You can't do this through mongoose, as mongoose and its models require connection to be made to a particular database and not to just the root db server. Anyways, I didn't want to give up mongoose for my own project so I just had to resort to initializing the db connection and its models per HTTP request by the user and closing the connection upon response.

查看更多
登录 后发表回答