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

谁说胖子不能爱 提交于 2019-12-12 12:08:17

问题


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?


回答1:


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




回答2:


From Cannot unit test my model in sailsjs:

"Once Sails app is lifted, you will have your models available automatically...

And in your case, your first line overrides the User model which would be otherwise constructed by Sails.js, that's why even though you have an object it's not a Waterline model."




回答3:


I know this is old but, for completeness:

You set

var Locations = ...

But but you call

Location.create()

(no 's') so you just have a typo.



来源:https://stackoverflow.com/questions/22941765/sailsjs-best-practice-to-seed-database-with-data-before-other-models-are-initial

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!