Search code examples
node.jspostgresqlmodelsails.jswaterline

How to add an attribute with array of integers data type in sails.js model?


I'm using sails with postgresql and I have a user with an array of group ids. I want to save the group id in the user table. my user model is like:

    module.exports = {
  attributes: {
    first_name: {
      type: 'string'
    },

    last_name: {
      type: 'string'
    },
    company: {
      type: 'string'
    },
    password: {
      type: 'string',
      minLength: 6,
      required: true,
      columnName: "password"
    },

    user_groups: {
      model: 'groups',
    }
  }

but when I send a request like [2] I get the error of :

Could not use specified user_groups. Expecting an id representing the associated record, or null to indicate there will be no associated record. But the specified value is not a valid user_groups. Instead of a number (the expected pk type), got: [ 2 ]


Solution

  • To do a many-to-one association in Waterline, the syntax is a little different. In that object for that field, you need collection and via (the name of the corresponding field in the associated collection). So in the User (for convention, I am making the model name singular and PascalCase) it would be something like:

    user_groups: {
        collection: 'Group',
        via: 'users'
    }
    

    While in the Group model, you have:

    users: {
        collection: 'User',
        via: 'user_groups'
    }