Dave Sag
Dave Sag

Reputation: 13486

What is the recommended way to initialise a MongoDB database and user for a Sails.js application?

I am exploring writing a Sails.js application that talks to a mongodb data store. I've got it all working just fine but I'd like to be able to add some sort of initialisation process that runs at the npm install point that runs analogously to rake admin:create in the Rails world.

I'm guessing that this could be done by via a grunt task somehow, but I figured, before I roll my own solution, I'd ask other Sails / MongoDB users what they actually do in the real-world and see if a consistent, or best-practice solution has emerged.

Upvotes: 1

Views: 1298

Answers (2)

sgress454
sgress454

Reputation: 24948

Database initialization for Sails apps is typically done in the config/bootstrap.js file. A simple one would be something like:

module.exports = function(cb) {

    User.findOrCreate(
        // Search for user with "admin" flag
        {admin: true},
        // Create one if no such user is found
        {admin: true, name: 'Admin User', ...}
    ).exec(cb);

}

The bootstrap will run only when Sails is lifted, and the server won't start until the callback is executed. If you send anything as the first argument to the callback, it'll be considered an error (like most standard Node callbacks) which will halt lifting of the server.

Note that you can't create the actual database with Waterline. A Grunt task would be a fine place for that, but you have to consider that Grunt doesn't have access to the Sails config, so you'd have to hard-code the name of the database to use, or find some other way to make it configurable. This could have implications for different environments (i.e. development vs. production). In our projects at Balderdash, we typically leave database creation as a manual step for the developer after they check out the code, and then use bootstrap.js to initialize the data. This allows the developer to maintain their own database settings using config/local.js.

All that being said, I can see the value in setting up a Grunt task for creating a db for production, to make it easier to deploy your Sails app to its final destination.

Upvotes: 3

InternalFX
InternalFX

Reputation: 1485

I personally think it was a wise decision by the sails.js team to use Grunt. Grunt provides a reliable and flexible solution to whatever automation you need.

I use grunt for everything in my sails.js projects including....

  • Importing data from legacy databases
  • Compiling sass (even though sails uses less by default)
  • Compiling coffeescript
  • Assembling knockout templates
  • Loading indexes into elasticsearch

You wont be disappointed using Grunt, It's pretty easy to get started with....So get to it!

Upvotes: 1

Related Questions