SailsJS 最佳实践,在其他模型初始化之前用数据播种数据库 [英] SailsJS best practice to seed database with data before other Models are initialized
问题描述
有一个模型,所有其他模型都假设它存在.它应该在调用任何 API 函数之前进行初始化.
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) 在 api/models 中定义模型,我们称之为 Location.js
1) Define model in api/models, let's call it Location.js
2) 将以下内容添加到 bootstrap.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);
});
}
问题 1这是进行初始数据库播种的正确方法吗?
Question 1 Is it the right way to do initial database seeding?
我收到此错误:
Locations.create(locationsObj, function locationsObj(err, locations) {
^
TypeError: Object #<bject> has no method 'create'
问题 2bootstrap的cb函数是如何工作的?如果出现错误怎么办?
Question 2 How does the cb function of bootstrap work? what if there as an error, what to do?
推荐答案
风帆模型全球可用;所以你不需要在 bootstrap.js 中要求.
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)
在 config/models.js 中包含种子函数.您在此文件中声明的方法将扩展到您的所有模型.链接:种子方法要点
定义种子将在您的模型中使用的数据链接:模型的种子数据
Define de data the seed will consume in your model Link: Model's seed data
使用异步调用 config/bootstrap.js 中的种子方法.链接:调用方法
Call the seed method in config/bootstrap.js using async. Link: Calling method
更新
也看看这个威胁:最佳将表更改迁移到生产 Sailsjs 表的方法
这篇关于SailsJS 最佳实践,在其他模型初始化之前用数据播种数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!