SailsJS最佳实践是在初始化其他模型之前使用数据对数据库进行种子设定

use*_*106 4 sails.js

有一个模型,所有其他模型都假设它存在.它应该在调用任何API函数之前初始化.

我这样做的方式(它不起作用):

1)在api/models中定义模型,我们称之为Location.js

2)将以下内容添加到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);
        });
  }
Run Code Online (Sandbox Code Playgroud)

问题1 这是进行初始数据库播种的正确方法吗?

我收到此错误:

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

问题2 bootstrap 的cb功能如何工作?如果出现错误怎么办?

Jua*_*ano 10

帆模型在全球范围内可用; 所以你不需要在bootstrap.js.

这是我用来为我的数据库播种的东西.(请参阅我附上的链接以获取要点)

  1. 在config/models.js中包含种子函数.您在此文件中声明的方法将扩展到您的所有模型. 链接:种子方法要点

  2. 定义种子将在模型中使用的de数据链接:模型的种子数据

  3. 使用async调用config/bootstrap.js中的seed方法.链接:调用方法

UPDATE

另请参阅此威胁:将表更改迁移到生产sailsjs表的最佳方法