有一个模型,所有其他模型都假定它的存在.它应该在任何API函数被调用之前被初始化。
我的方法是这样做的(它不工作)。
1) 在apimodels中定义模型, 让我们把它叫做... ... 位置.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);
});
}
问题1做数据库初始种子的方法正确吗?
我得到这个错误。
Locations.create(locationsObj, function locationsObj(err, locations) {
^
TypeError: Object #<bject> has no method 'create'
问题2如何 cb 功能的引导工作?如果有作为一个错误,怎么办?
sails模型是全球可用的;所以你不需要在bootstrap.js中要求。
我就是用这个来做数据库的种子。(请看我附上的链接去看要点)
在configmodels.js中包含种子函数。你在这个文件中声明的方法将被扩展到你所有的模型。链接。种子方法要旨
定义种子在模型中消耗的数据。链接。模型的种子数据
在configbootstrap.js中使用async调用种子方法。链接。调用方法
也来看看这个威胁。将表的变化迁移到生产的sailsjs表的最佳方法
"一旦Sails应用解除,你的模型就会自动可用......。
而在你的例子中,你的第一行覆盖了用户模型,而用户模型本来是由Sails.js构建的,这就是为什么即使你有一个对象,它也不是一个Waterline模型。"
我知道这是旧的,但是,为了完整。
你设置
var Locations = ...
但是,但你叫
Location.create()
(没有's')所以你只是打错了。
在configbootstrap.js中,你可以直接写你的种子。看看下面的例子。
await sails.models.role.createEach([
{
name: 'Admin',
},
{
name: 'Normal-user',
},
]);
这里'role'是创建的表的名字,而不是模型的名字。