Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SailsJS best practice to seed database with data before other Models are initialized

Tags:

sails.js

There is a model that all other models assume its existence. It should be initialized before any API function is called.

The way I do this (it doesn't work):

1) Define model in api/models, let's call it Location.js

2) Add the following to bootstrap.js

    var Locations = require('../api/models/Locations.js');

    module.exports.bootstrap = function (cb) {

      // seed the database with Locations
        var locationsObj = {
            country: 'Australia',
            states: ['Brisbane', 'Perth', 'Sydney']
        };
        Location.create(locationsObj, function locationsObj(err, locations) {
            if (err) {
                cb(err);
            }
            console.log('locations created: ', locations);
        });
  }

Question 1 Is it the right way to do initial database seeding?

I get this error:

Locations.create(locationsObj, function locationsObj(err, locations) {
          ^
TypeError: Object #<bject> has no method 'create'

Question 2 How does the cb function of bootstrap work? what if there as an error, what to do?

like image 202
user2867106 Avatar asked Dec 11 '22 06:12

user2867106


1 Answers

The sails models are globally available; so you don't need to require at bootstrap.js.

This is what I use to seed my database. (See the links I enclose to go to the gists)

  1. Include seed function at config/models.js. The methods you declare in this file will be extended to all your models. Link: Seed method gist

  2. Define de data the seed will consume in your model Link: Model's seed data

  3. Call the seed method in config/bootstrap.js using async. Link: Calling method

UPDATE

Have a look at this threat also: Best way to migrate table changes to production sailsjs tables

like image 116
Juan Solano Avatar answered Apr 15 '23 16:04

Juan Solano