kevinblanco
kevinblanco

Reputation: 779

Sails.js save multiple associations

I'm building a very simple API with sails which handles participants and teams . Teams might have several participants, so the API should accept multiple participants IDs to create the relationships when creating a new team.

Participant model

attributes: {

  name:{
    type : 'string',
    required : true
  },
  email : {
    type : 'email',
    required : true,
    unique : true,
  },
  age : {
    type : 'string'
  }

}

Team model

attributes: {

    name:{
        type : 'string',
        required : true
    },
    logo : {
        type : 'string'

    },
    participants:{
        model: 'participant'
    }
}

I can create a team and save the relationship successfully to one participant passing the following JSON to the API:

{
   "name" : "Best Team ever",
   "logo" : "http://...."
   "participants" : "546bc4136911426a093cb903"
}

But i'm having trouble to save the relationship to several participants, I've tried passing an array of IDs to the API but it doesn't save any relationship, either passing and object of IDs.

I would like to save the relationship to several participants on a single request.

Can i complete this behaviour with sails relationships and blueprints ? or I have to do it manually within the controller

Thanks in advance.

I'm using sails-mongo just in case.

Upvotes: 2

Views: 771

Answers (1)

Mandeep Singh
Mandeep Singh

Reputation: 8224

Yes its definitely possible. Just change your model as follow:

attributes: {

    name:{
        type : 'string',
        required : true
    },
    logo : {
        type : 'string'

    },
    participants:{
        collection: 'participant',
        via: 'id'
    }
}

Then you can pass array of participant ids when creating the team record. Please note that however, participants field will not be a part of the team collection at database level. Instead of that, waterline will automatically create another table containing mapping of participant id and team id. Name of the table will be something like participant_id__team_participant or something like that. When you fetch team using the blueprints, participant array will be populated. However, if you are using find of findOne to fetch team record, use the syntax below to fetch participants

Team.findOne()
.populate('participants')
.exec(function (err, team){
  // do something here
})

Hope it solves your problem. Let me know if you still face any issues

Upvotes: 2

Related Questions