【问题标题】:How to seed data for a node+mongo app deployed to Heroku?如何为部署到 Heroku 的 node+mongo 应用程序播种数据?
【发布时间】:2015-11-13 05:00:40
【问题描述】:

我有一个以 MongoDB 作为数据库的 node express 应用程序。我想要一个可以运行的seed.js 文件来将初始数据填充到数据库中。我在本地机器上执行此操作没有问题。我只是在我的 seed.js 文件中编写 mongo 命令并运行它:

$ mongo localhost:27017/myApp seed.js

但是,当我将我的应用程序部署到 Heroku (包括 MongoLab)时,我不确定如何在那里播种数据。谷歌大部分时间都在引导我使用 Rails 的东西。

那么有没有一种简单的方法来为 Heroku MongoLab 播种数据,而无需编写脚本?

更新: 如果我尝试使用 heroku 的 MONGOLAB_URI 运行它,我会收到错误消息。

$ mongo mongodb://heroku_xxxx:xxxxx.mongolab.com:xxx/heroku_xxxx seed.js 

MongoDB shell version: 3.0.5
connecting to: mongodb://heroku_xxxxxxxx
2015-08-19T21:44:22.694+0100 E QUERY    Error: More than one ':' detected. If this is an ipv6 address, it needs to be surrounded by '[' and ']'; heroku_xxxxxxxxxxxxx
    at connect (src/mongo/shell/mongo.js:181:14)
    at (connect):1:6 at src/mongo/shell/mongo.js:181
exception: connect failed

【问题讨论】:

  • mongodb://user:pass@host:port/db URI 格式不适用于 mongo shell。您需要将其分解: mongo host:port/db -u user -p pass

标签: node.js mongodb heroku mlab seeding


【解决方案1】:

这里是关于如何使用 mongo 命令为部署到 Heroku 的应用运行 seed.js 文件的完整答案,感谢 pneumee 和 hunterloftis:

  1. 在您的应用目录中运行 $ heroku config 获取您的 MONGOLAB_URI
  2. MONGOLAB_URI 变量的格式为mongodb://user:pass@host:port/db。 使用这些不同的部分将正确的终端命令粘在一起来运行 seed.js 文件:

    $ mongo host:port/db -u user -p pass yourSeedFile.js
    

【讨论】:

    【解决方案2】:

    如果您运行heroku config -a yourapp,您将看到您的 mongolab 实例的连接字符串。然后,您可以通过您在本地使用的相同 mongo 客户端连接到该数据库,运行相同的 seed.js

    【讨论】:

    • 谢谢。我了解您的解决方案,这正是我想要的。不幸的是,当我这样做时出现错误,并且我不理解错误消息中建议的修复。我将其包含在问题中。
    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 2014-12-13
    • 2017-11-27
    • 2018-01-27
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多