首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Node + Express + Sequelize + (Mysql或Postgres)构建SaaS产品

使用Node + Express + Sequelize + (Mysql或Postgres)构建SaaS产品
EN

Stack Overflow用户
提问于 2018-06-04 23:58:33
回答 1查看 1.3K关注 0票数 0

我们正计划建立一个基于SaaS的产品,所以在经过大量的搜索之后,我们发现有三种设计SaaS产品的数据库方法。

  1. 每个租户的单独数据库
  2. 每个租户的单独模式
  3. 共享模式和所有租户的一个数据库(但将使用tenant_id进行查询)

所以我们计划进入备选方案2,

因此,最初我们使用Mysql,但没有找到如何在mysql中获取多个模式,而是使用续订为ORM。

在大量搜索之后,我们发现许多基于多租户的产品正在使用postgresql进行强大的模式方法,因此我们尝试了这个库:

https://github.com/westmark/sequelize-multi-tenant-enhancer

我们尝试了基于多模式的方法,但是数据没有按照租户显示,我还在github中打开了一个问题,

因此,如果您有任何想法,或任何帖子,帮助我建立一个SaaS产品,帮助我

注意:我的堆栈:节点+ Express +角+ Mysql或Postgres

我的问题是如何在postgres中使用多个模式?

EN

回答 1

Stack Overflow用户

发布于 2018-06-06 05:59:02

最后,我决定使用选项2,我移到Postgresql而不是mysql,因为Postgresql有基于模式的方法!

现在我的最后代码是:

代码语言:javascript
复制
const postgresDB = new Sequelize('postgres://localhost:5432/test_enduser');

postgresDB.authenticate().then((err) => {
  if (err) {
    console.log('There is connection in ERROR.');
  } else {
    console.log('Postgres Connection has been established successfully');
  }
});

postgresDB.define('inventory', {
  name: Sequelize.STRING,
});

const createSchema = () => {
  Business.findAll({
    raw: true,
  }).then((data) => {
    data.forEach((client) => {
      postgresDB.createSchema(client.code).then(() => {
        Object.keys(postgresDB.models).forEach((currentItem) => {
          postgresDB.models[currentItem].schema(client.code).sync();
        });
        // new schema is created
        console.log('Postgres schema created');
      }).catch((err) => {
        console.log(err.message);
      });
    });
  });
};
createSchema();


// apis
exports.getAllBusiness = (req, res) => {
  postgresDB.models.inventory.schema(req.user.code).findAll()
    .then((results) => {
      res.send(results);
    });
};

exports.postBusiness = (req, res) => {
  const user = {
    name: req.body.name,
  };
  postgresDB.models.inventory.schema(req.user.code).create(user)
    .then(data => res.status(200).send(data))
    .catch(Sequelize.ValidationError, err => res.status(422).send(err.errors[0].message))
    .catch(err => res.status(400).send(err.message));
};

我正在设置postgres连接

为了测试,我正在创建一个名为“库存”的表。

在我的应用程序中,一个在线程序来了,他注册了,而我注册的时候,我正在将业务代码存储到我的业务表中(业务表来自独立的DB,这是一个超级主要的应用程序DB),所以我正在查找业务代码和循环,并在postgres中创建动态模式

现在看看我的api,我正在基于req.user.code(从登录会话)执行CRUD,最后根据特定的模式来匹配显示数据,

因此,最后,我为每个客户端提供了独立的模式。

谢谢!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50690280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档