postgresql 如何在 Sequelize 中创建一个表以使用 NodeJS 存储在 Postgressql 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46341495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:38:26  来源:igfitidea点击:

How to Create a table in Sequelize to store in Postgressql with NodeJS

node.jspostgresqlexpresssequelize.jsrdbms

提问by Kannan T

Am a newbie to Postgres and Sequelize i have successfully connected to DB trying to create a table in DB that is where am struck am getting an error the tablename doesn't exist

我是 Postgres 和 Sequelize 的新手,我已经成功连接到数据库,试图在数据库中创建一个表,我在那里遇到了一个错误,表名不存在

sequelize.authenticate().then(() => {
  console.log("Success!");
  var News = sequelize.define('likes', {
    title: {
      type: Sequelize.STRING
    },
    content: {
      type: Sequelize.STRING
    }
    }, {
     freezeTableName: true
   });
   News.create({
     title: 'Getting Started with PostgreSQL and Sequelize',
     content: 'Hello there'
   });
   News.findAll({}).then((data) => {
     console.log(data);
   }).catch((err) => {
     console.log(err);
   });
}).catch((err) => {
  console.log(err);
}); 

Where am making a mistake? It says error: relation "likes" doesn't exist. Any kind of help is appreciated

哪里出错了?它说错误:关系“喜欢”不存在。任何形式的帮助表示赞赏

回答by Zeke Alexandre Nierenberg

Sequelize only creates tables through syncor migrations. Your model, Newshas a syncmethod, that when called will do one of a few things

Sequelize 仅通过sync或迁移创建表。你的模型News有一个sync方法,当被调用时会做一些事情之一

If called with no params, it will create the table if it doesn't exist

如果不带参数调用,如果表不存在,它将创建表

if called like this News.sync({ force: true })it will drop the current table if it exists and make a new one.

如果这样调用News.sync({ force: true }),它将删除当前表(如果存在)并创建一个新表。

if called like this News.sync({ alter: true })it will add any new fields that are not in the model yet (this is a v4 feature).

如果这样调用News.sync({ alter: true }),它将添加模型中尚未包含的任何新字段(这是 v4 功能)。

These techniques can be useful when rapidly prototyping, but the best solution is to use migrations. Migrations allow you to keep track of changes to your database across development, different git branches, and production. Its by far the best solution, but does come with a small amount of upfront cost and buy-in.

这些技术在快速原型制作时很有用,但最好的解决方案是使用迁移。迁移允许您跟踪跨开发、不同 git 分支和生产的数据库更改。它迄今为止是最好的解决方案,但确实需要少量的前期成本和购买。

If you're working on a hackathon style project, I'd just go with {alter: true}, but if you're building something you're going to be working on for a while, definitely get to know the migrations API.

如果你在做一个黑客马拉松风格的项目,我会选择{alter: true},但如果你正在构建一些你将要工作一段时间的东西,一定要了解迁移 API