如何迁移 sails.js 中的数据库?

问题描述 投票:0回答:2

所以我创建了一个新的 Sails.js 项目,然后运行

$ sails generate api user

就像建议的加载页面一样。但现在当我用

sails lift
启动服务器时,我收到错误:

sails lift               

info: Starting app...

-----------------------------------------------------------------

 Excuse my interruption, but it looks like this app
 does not have a project-wide "migrate" setting configured yet.
 (perhaps this is the first time you're lifting it with models?)

 In short, this setting controls whether/how Sails will attempt to automatically
 rebuild the tables/collections/sets/etc. in your database schema.
 You can read more about the "migrate" setting here:
 http://sailsjs.org/#/documentation/concepts/ORM/model-settings.html?q=migrate

 In a production environment (NODE_ENV==="production") Sails always uses
 migrate:"safe" to protect inadvertent deletion of your data.
 However during development, you have a few other options for convenience:

 1. safe  - never auto-migrate my database(s). I will do it myself (by hand) 
 2. alter - auto-migrate, but attempt to keep my existing data (experimental)
 3. drop  - wipe/drop ALL my data and rebuild models every time I lift Sails

What would you like Sails to do?

info: To skip this prompt in the future, set `sails.config.models.migrate`.
info: (conventionally, this is done in `config/models.js`)

是否有我必须运行的 sails migrate 命令?我知道在 Rails 中我会做类似

rake db:migrate
的事情。生成命令后,sails 中的程序是什么?

javascript node.js sails.js
2个回答
11
投票

这不是错误,它只是告诉您没有指定默认迁移策略。

打开即可

config/models.js

并取消注释显示“迁移”的行,如上图所示。

就像“弹出窗口”告诉您的信息一样,您可以选择

  • 安全
  • 改变

Drop 将删除所有表并重新创建它们,这对于新项目很有用,并且您希望始终播种新的虚拟数据。

Alter 将尝试保留您的数据,但如果您在模型中这样做,则会对表进行更改。如果 sails 无法保留数据,则会将其删除。

Safe,顾名思义,最安全。它对你的桌子没有任何作用。

如果您想对不同的表采取不同的操作,您可以直接在模型中指定相同的选项,这将仅覆盖该模型的默认设置。

因此,假设您有一个

User
模型并希望保留该数据,但希望每次都重新创建所有其他模型
sails lift
,您应该添加

migrate: 'safe'

直接连接到模型并使用

drop
作为默认策略。

我个人喜欢

alter
,但这可能有些固执己见。

您不需要做任何其他事情。如果有模型并且 migrate 设置为

drop
alter
,则运行
sails lift
时将迁移该模型。

您可以在此处

了解有关模型设置的更多信息

作为旁注,您可以通过设置来查看帆在提升过程中对桌子的确切作用

log: 'verbose'

在您的 config/env/development.js 文件中:


0
投票

我创建了这样一个简单的迁移模块

sails-db-migrate-generator 是一个功能强大的工具,可以与 Sails 命令行界面结合使用,通过单个命令轻松创建缺失的 db-migrate 迁移。在内部, sails-db-migrate-generator 使用 db-migrate。

此包扫描现有的迁移文件和模型树,然后在单个文件中自动生成丢失的迁移。它使用异步库按顺序正确处理迁移。

这是一个示例用法:

$ npm i -g sails-db-migrate-generator

参数:

migration-label (optional), default: "migrations-generator-processed"
migrationsPath (optional), default: "./migrations"
modelsPath (optional), default: "./api/models"

$ sails-migrate --modelsPath="./models" --migrationsPath="./migrations"

© www.soinside.com 2019 - 2024. All rights reserved.