【问题标题】:Sails.js beforeValidate() emptying value parameterSails.js beforeValidate() 清空值参数
【发布时间】:2015-02-19 19:49:28
【问题描述】:

我遇到了 beforeValidate() 的问题,在网上找不到任何答案。我的模型有两个关系属性,需要 POST 数据中的 id 号。如果用户 POST 字符串,他们会收到验证错误。我想让用户 POST 字符串数据,然后在 beforeValidate() 中使用 findOrCreate() 查找或创建属性的相关模型,然后用相关模型的 ID 覆盖 POST 数据的属性。

我有以下型号:

attributes: {
    reporter    : { model: 'reporter', required: true },
    location    : { model: 'location', required: true },
    line        : { type: 'boolean', required: true, defaultsTo: true },
    count       : { type: 'int', required: true, defaultsTo: 0},
    composition : { type: 'int', required: true, defaultsTo: 3}
  },

  beforeValidate: function(values, next) {
    if (typeof values.reporter !== 'number') {
        Reporter.findOrCreate({name: values.reporter}).exec(function(data){
            console.log(data)
            values.reporter = data.id;
        })
    };
    next();
  },

我正在将此数据发布到模型的 create() 默认蓝图端点:

{
"location":"Harry's",
"reporter":"tim",
"count":30,
"composition":3,
"line":false
}

当我在 beforeValidate() 中记录上述值时,我得到了这个:

{ location: NaN,
reporter: NaN,
count: '30',
composition: '3',
line: false }

当我用 ID 替换“位置”和“记者”时,我没有收到任何错误。为什么字符串值在 beforeValidate() 函数中被剥离?

【问题讨论】:

    标签: javascript sails.js


    【解决方案1】:

    也许你需要 POST(create) 到端点位置模型,然后 POST(create) 到报告模型,然后 POST YOUMODEL/id/reporterID,POST YOUMODEL/id/location ID

    【讨论】:

    • 我认为这不是问题所在。当我发布整数时,无论该主键是否存在模型,当我记录值时,该属性仍设置为整数。不过谢谢你的想法。
    • 世界上哪里有内置类方法的文档呢? (beforeCreatebeforeValidate 等)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多