validation - Sails.js 和水线 : dynamic validation by DB request

标签 validation sails.js waterline

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

我想对 1 个属性使用 in 验证器来验证插入到“文章”模型中的数据。 之前,我使用生命周期回调(尤其是 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 字段的配置当然会抛出错误,因为它不应该使用函数,尤其是你的函数不返回任何东西,也如果你强制它返回一些东西,它会返回 Theme.find()... 所做的 Promise

尝试使用不同的方法。存在 Model Lifecycle Callbacks .您可以使用 beforeCreatebeforeValidate 来手动检查您的动态 Theme,如果它无效,则返回错误。

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

关于validation - Sails.js 和水线 : dynamic validation by DB request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31195098/

相关文章:

html - 为什么一些主要网站使用无效的 HTML?

c# - 如何显示服务器端验证错误消息?

javascript - sails.js 中 Controller 与 typescript (或不 typescript )之间的继承

logging - winston 文件传输日志转义字符

sails.js - lodash @'~2.4.1' 是怎么回事?

unit-testing - Grails mock :与 Controller 解耦验证

c# - 构建验证服务层

sails.js - `req.options` 在 SailsJS 中的作用是什么?

node.js - sails js在ubuntu中运行testProjects问题

sql - MSSQL : Finding all items between two dates