MongoDB 的初始数据库结构/数据 + NodeJS Web 应用程序
我正在 Node.js 中开发一个 Web 应用程序,并以 MongoDB 作为后端。我想知道的是,用于创建初始集合并用初始数据(例如名称白名单或预定义常量列表)填充它们的普遍接受的程序(如果存在)是什么。
据我所知,只要将数据插入数据库并且插入的集合尚不存在,MongoDB 就会隐式创建集合。让这些隐式插入负责集合创建是标准做法吗?或者使用 MongoDB 的人是否有脚本设置来构建主要结构并插入任何所需的初始数据? (例如,当使用 MySQL 时,我有一个 .sql 脚本,我可以运行该脚本来转储和重建/重新填充数据库)。
感谢您的帮助。
米哈伊
I'm developing a web application in Node.js with MongoDB as the back end. What I wanted to know is, what is the generally accepted procedure, if any exists, for creating initial collections and populating them with initial data such as a white list for names or lists of predefined constants.
From what I have seen, MongoDB creates collections implicitly any time data is inserted into the database and the collection being inserted into doesn't already exist. Is it standard to let these implicit insertions take care of collection creation, or do people using MongoDB have scripts setup which build the main structure and insert any required initial data? (For example, when using MySQL I'd have a .sql script which I can run to dump and rebuild /repopulate the database from scratch).
Thank you for any help.
MHY
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有数据,这篇关于 SO 的文章可能会让您感兴趣。但由于 Mongo 理解 JavaScript,因此您可以轻松编写脚本来为您准备数据。
创造一切不存在的东西是 Mongo 的本质。这允许非常灵活和敏捷的开发,因为您不受类型的限制,也不需要在处理之前检查
table x
是否已经存在。如果您需要动态创建集合,只需从数据库中获取它并使用它(无论它是否存在)。如果您正在查找某个对象,请务必检查它(不为空或某个键是否存在),因为如果您使用空对象,它可能会影响您的代码。
If you have data, this post on SO might be interresting for you. But since Mongo understands JavaScript, you can easily write a script that prepares the data for you.
It's the nature of Mongo to create everything that does not exist. This allows a very flexible and agile development since you are not constrainted to types or need to check if
table x
already exists before working on it. If you need to create collections dynamically, just get it from the database and work it if (no matter if it exists or not).If you are looking for a certain object, be sure to check it (not null or if a certain key exists) because it may affect your code if you work with null objects.
绝对没有理由仅仅使用安装脚本来显示集合和数据库。数据库和集合的创建都是延迟完成的。
请记住,MongoDB 是一个完全无模式的文档存储,因此甚至无法提前设置特定模式。
有一些工具可用于转储和恢复 mongo 提供的数据库内容。
现在,如果您的应用程序需要初始数据(如您建议的配置参数或白名单),通常最佳实践是让您的应用程序组件根据需要设置自己的数据并提供数据迁移路径。
There's is absolutely no reason to use setup scripts merely to make collections and databases appear. Both DB and collection creation is done lazily.
Rember that MongoDB is a completely schema free document store so there's no way to even setup a specific schema in advance.
There are tools available to dump and restore database content supplied with mongo.
Now, if your application needs initial data (like configuration parameters or whitelists like you suggest) it's usually best practice to have your application components set up there own data as needed and offer data migration paths as well.