gpt4 book ai didi

node.js - sails.js 嵌套模型

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:49 27 4
gpt4 key购买 nike

在 sails.js 0.10 中,我正在尝试执行以下操作

// user.js
module.exports = {
attributes: {

uuid: {
type: 'string',
primaryKey: true,
required: true
} ,
profile: {

firstname: 'string',
lastname: 'string',
birthdate: 'date',
required: true
}
}
};

我在尝试创建用户时遇到错误,sailsJS 无法识别“配置文件”属性。我不确定 sails 是否支持嵌套的 JSON 结构,如果支持,我不确定如何构造它。

error: Sent 500 ("Server Error") response
error: Error: Unknown rule: firstname

我已经尝试了以下但它也失败了

// user.js
module.exports = {
attributes: {

uuid: {
type: 'string',
primaryKey: true,
required: true
} ,
profile: {

firstname: {type: 'string'},
lastname: {type: 'string'},
birthdate: 'date',
required: true
}
}
};

我知道 sailsJS 0.10 有一个名为“JSON”的属性,但不确定它如何适合这个模块。

最佳答案

Waterline 不支持定义嵌套模式,但您可以使用 json 类型在模型中存储嵌入对象。所以,你会这样做:

profile: {
type: 'json',
required: true
}

然后您可以创建 User 实例,例如:

User.create({profile: {firstName: 'John', lastName: 'Doe'}})

区别在于 firstNamelastName 字段不会被验证。如果你想验证嵌入的 profile 对象的架构是否符合你的要求,你必须在你的模型类中实现 beforeValidate() 生命周期回调:

attributes: {},
beforeValidate: function(values, cb) {
// If a profile is being saved to the user...
if (values.profile) {
// Validate that the values.profile data matches your desired schema,
// and if not call cb('profile is no good');
// otherwise call cb();
}
}

关于node.js - sails.js 嵌套模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020055/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com