【发布时间】: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