Sails.js 和 Waterline:通过数据库请求进行动态验证

Sails.js and Waterline: dynamic validation by DB request

我将 Sails 11.1 和 Waterline 2.11.2 与 MongoDB 数据库一起使用。

我想对 1 个属性使用 in 验证器来验证插入到我的 "Article" 模型中的数据。 之前,我使用生命周期回调(尤其是 beforeCreatebeforeUpdate)来完成这项工作,但它会产生双重代码。

这里是模型,只截断了相关属性:

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 转换为字符串,但没有别的......

我做错了什么?或者这是一个错误?

您也可以在这里查看我的问题:Waterline GitHub issues

模型在 attributes 范围内 in 字段的配置当然会抛出错误,因为它不应该使用函数,尤其是你的函数不是 return 任何东西,也如果你强迫它 return 某些东西,它会 return Promise Theme.find()... 所做的。

尝试使用不同的方法。存在 Model Lifecycle Callbacks。您可以使用 beforeCreatebeforeValidate 之类的东西来手动检查您的动态 Theme,如果它无效,return 一个错误。

或者,如果可以使用标准数据库关系实现,则只需使用简单的数据库关系即可。