node.js - 使用 sails js 版本 1 提升后的动态数据库连接

标签 node.js sails.js waterline

我只想要MYsql的解决方案

我想根据请求切换数据库 我已经在以前的 sails 版本中实现了它,但是有了这个新版本 (1.0.0) 我做不到 sails.js - I want to add DB connection dynamically after sails lift

没有它的文档

我有主数据库可以说 DB_A,我将其用作默认数据存储以在用户拥有自己的数据库进行交互后对用户进行身份验证 在提升之后,它可以是系统中存在的任何数据库,用户可以连接和获取

我发现的几个选项

1) 重新加载orm

2) 创建管理器

但不知道如何使用它,因为没有建议

谁能帮帮我

最佳答案

我在 sails 应用程序中使用 PostgreSQL 时遇到了类似的问题。我 在下面找到了解决方法。 即 npm 安装 pg。 在你的情况下安装 mysql 插件即 npm i mysql

我在 sails 应用程序 Controller 文件夹中创建了 dbconnections.js

const a = {
  host: 'abc.com',
  port: 'xxxx',
  database: 'xxxx',
  user: 'xxxx',
  password: 'xxxx'
}

const b = {
  host: 'ecd.com',
 port: 'xxxx',
  database: 'xxxx',
  user: 'xxxx',
  password: 'xxxx'
}


module.exports = { a: a, b: b};

然后在我的其他 Controller 中,我使用 pg 插件来匹配用户传递的数据库 通过 api 环境

即在我的另一个 Controller 中

var sourceFile = require('./dbconnections.js');

const {
      Client
    } = require('pg');

对于您的情况,您可以遵循此 https://www.npmjs.com/package/mysql到 创建连接对象并按照以下逻辑动态连接 到不同的数据库

    var match_env;

    for (x in sourceFile) {

      if (x === env) {
        match_env = sourceFile[x];

      }
    }

    const client = new Client(match_env)

现在客户端对象将拥有所有的 postgresql 交易 执行,即 客户端连接() const qry = "select * from person where city="newyork"; client.query(qry, function (err, resp) {

    console.log("before", client)

    client.end();
    console.log("after", client)
    //user = JSON.parse(user);
    if (err) {
      return res.json({
        error: err
      });
    }
    if (resp === undefined) {
      return res.notFound();
    } else
      console.log(resp);
    return res.json({
      userData: resp.rows
    });

  }

);

根据用例,我们可以将上面的代码移动到其他js文件并调用 作为 尽可能多的 Controller ,这将适用于多个数据库 sails 应用程序中 postgres sql 的连接。

关于node.js - 使用 sails js 版本 1 提升后的动态数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51456218/

相关文章:

node.js - Express 发送 base-64 编码的 png 图像

node.js - Nightmare 卡在goto()上

javascript - 通过字符串名称访问 Sails.js 模型

node.js - SailsJS - 蓝图关联 "add to"

node.js - Sails.js 中的唯一属性失败

javascript - NodeJS 中的 Promise 和函数没有返回任何内容

javascript - 从带有缺失值的制表符分隔的 txt 文件中收集数据

many-to-many - 如何计算与水线/sails 的关联大小?

javascript - Sails ORM 不理解数值?

mongodb - Sails JS 和 Mongodb 唯一属性被忽略