sails.js嵌套模型

 zj5415 发布于 2023-01-11 19:51

在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无法识别"profile"属性.我不确定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
     }
  }
};

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

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

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

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

    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();
        }
    }
    

    2023-01-11 19:53 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有