在MEAN App中为每个用户创建一个专用数据库 [英] Create a dedicated Database per user in a MEAN App

查看:156
本文介绍了在MEAN App中为每个用户创建一个专用数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一个需要每个注册用户使用专用数据库的项目。我更喜欢与MongoDB合作,所以我将它用于相同的(我对吗?)。该应用程序使用 REST API 作为后端(用 Node Express 编写),并使用 AngularJS App 。因此,我想做的是每当用户向某个API端点发出请求,例如对 api / user / mydata 的GET请求时,我都会创建一个与他的连接特定的数据库,获取所需的数据,关闭连接并返回获取的数据作为响应。 这种方法正确吗?另外,我使用 Mongoose 作为ODM,并使用 PassportJS 进行用户身份验证。而且,我的应用程序的用户是互斥的。用户与任何其他注册用户之间没有数据连接。

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.

推荐答案

有一种方法可以做到这一点,但只有不使用猫鼬。您必须使用 mongodb 节点模块创建到MongoDB服务器的根连接(注意它,而不是到该服务器上的特定数据库),然后可以根据查询要求在数据库之间进行切换无需在每个数据库中创建新连接,如下所示:

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();
});

您不能通过猫鼬来做到这一点,因为猫鼬及其模型需要与特定的数据库,而不仅仅是根数据库服务器。无论如何,我不想为自己的项目放弃猫鼬,所​​以我只得诉诸于用户根据HTTP请求初始化数据库连接及其模型,并在响应后关闭连接。

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.

这篇关于在MEAN App中为每个用户创建一个专用数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆