sails.js 嵌套模型 [英] sails.js nested models
问题描述
在sails.js 0.10中,我正在尝试执行以下操作
In sails.js 0.10 I'm trying to do the following
// user.js
module.exports = {
attributes: {
uuid: {
type: 'string',
primaryKey: true,
required: true
} ,
profile: {
firstname: 'string',
lastname: 'string',
birthdate: 'date',
required: true
}
}
};
我在尝试创建用户时遇到错误,sailsJS 无法识别profile"属性.我不确定sails 是否支持嵌套的JSON 结构,如果支持,我不确定如何构造它.
I'm getting an error when trying to create a user and sailsJS doesn't recognize the "profile" attribute. I'm not sure if sails supports the nested JSON structure, and if it does I'm not sure how to structure it.
error: Sent 500 ("Server Error") response
error: Error: Unknown rule: firstname
我尝试了以下方法,但也失败了
I've tried the following but it failed too
// 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"的属性,但不确定它如何适合这个模块.
I know there is an attribute called "JSON" with sailsJS 0.10, but not sure how that will fit this module.
推荐答案
Waterline 不支持定义嵌套模式,但您可以使用 json
类型在模型中存储嵌入的对象.所以,你会这样做:
Waterline doesn't support defining nested schemas, but you can use the json
type to store embedded objects in your model. So, you would do:
profile: {
type: 'json',
required: true
}
然后你可以创建像这样的用户实例:
And then you could create User instances like:
User.create({profile: {firstName: 'John', lastName: 'Doe'}})
区别在于 firstName
和 lastName
字段不会被验证.如果您想验证嵌入的 profile
对象的架构是否与您想要的匹配,您必须在模型类中实现 beforeValidate()
生命周期回调:
the difference is that the firstName
and lastName
fields won't be validated. If you want to validate that the schema of the embedded profile
object matches what you want, you'll have to implement the beforeValidate()
lifecycle callback in your model class:
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();
}
}
这篇关于sails.js 嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!