简体   繁体   中英

Initial DB structure / data for MongoDB + NodeJS web application

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM