【发布时间】:2015-09-20 14:30:08
【问题描述】:
我将 Sails 11.1 和 Waterline 2.11.2 与 MongoDB 数据库一起使用。
我想使用in 1 个属性的验证器来验证插入到我的“文章”模型中的数据。
之前,我使用生命周期回调(尤其是beforeCreate 和beforeUpdate)来完成这项工作,但它会产生双重代码。
这里有模型,只截断了相关属性:
module.exports =
{
schema: true,
autoCreatedAt: false,
autoUpdatedAt: false,
attributes:
{
theme:
{
model: 'Theme',
required: true
}
}
}
我知道如何静态定义它:
in: ['something', 'something other']
我知道如何调用我在constants.js 文件中定义的常量:
defaultsTo: function ()
{
return String(sails.config.constants.articleDefaultTheme);
}
但我想在我的数据库中获取所有主题,以进行动态in 验证。所以,我写了这个:
theme:
{
model: 'Theme',
required: true,
in: function ()
{
Theme.find()
.exec(function (err, themes)
{
if (err)
{
return next({ error: 'DB error' });
}
else if (themes.length === 0)
{
return next({ error: 'themes not found' });
}
else
{
var theme_ids = [];
themes.forEach(function (theme, i)
{
theme_ids[i] = theme.theme_id;
});
return theme_ids;
}
});
}
}
但它不起作用,我总是出现“1 属性无效”错误。如果我静态地编写它们,或者如果我用另一个数据库请求签入beforeCreate 方法,它可以正常工作。
如果我sails.log()返回的变量,所有的主题id都在这里。
我尝试JSON.stringify()返回的变量,也尝试JSON.parse(JSON.stringify())它。我还尝试使用String() 函数将theme.theme_id 转换为字符串,但仅此而已...
我做错了什么?还是bug?
你也可以在这里查看我的问题:Waterline GitHub issues
【问题讨论】:
标签: validation sails.js waterline