sails.js嵌套模型

Kai*_*see 4 node.js sails.js waterline

在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
     }
  }
};
Run Code Online (Sandbox Code Playgroud)

我在尝试创建用户时遇到错误,sailsJS无法识别"profile"属性.我不确定sails是否支持嵌套的JSON结构,如果确实如此,我不确定如何构造它.

error: Sent 500 ("Server Error") response
error: Error: Unknown rule: firstname
Run Code Online (Sandbox Code Playgroud)

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

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

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

        firstname: {type: 'string'},
        lastname: {type: 'string'},
        birthdate: 'date',
        required: true
     }
  }
};
Run Code Online (Sandbox Code Playgroud)

我知道有一个名为"JSON"的属性,其中包含sailsJS 0.10,但不确定它是如何适合这个模块的.

sgr*_*454 13

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

profile: {
    type: 'json',
    required: true
}
Run Code Online (Sandbox Code Playgroud)

然后你可以创建用户实例,如:

User.create({profile: {firstName: 'John', lastName: 'Doe'}})
Run Code Online (Sandbox Code Playgroud)

区别在于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();
    }
}
Run Code Online (Sandbox Code Playgroud)