Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sails.js nested models

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

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

I know there is an attribute called "JSON" with sailsJS 0.10, but not sure how that will fit this module.

like image 497
Kaiusee Avatar asked Jun 03 '14 16:06

Kaiusee


1 Answers

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'}})

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();
    }
}
like image 162
sgress454 Avatar answered Sep 27 '22 19:09

sgress454