Tung
Tung

Reputation: 61

Associations of two Models in Sails.js

I am in trouble with linking of two models in sails. I had two models 'Singer' and 'Country'. In 'Singer' model, i had a attribute 'singer_country' that means id of 'Country' model. My problem is I can get attribute 'country_name' in 'Country' model when I show all singer's properties. I don't know how do it. Below is my code: My 'Singer' model

 module.exports = {

attributes: {
singer_name:{
    type: 'string',
    required: true,
    size: 50
},
singer_realname:{
    type: 'string',
    size: 50
},
singer_gender:{
    type: 'string',
    enum: ['Male', 'Female'],
    defaultsTo: 'Male'
},
singer_brithday:{
    type: 'int'
},
singer_image:{
    type: 'string'
},
singer_description:{
    type: 'string'
},
singer_country:{
    type: 'string'
}

}
};

My 'Country' model:

  module.exports = {

attributes: {
country_name: {
    type: 'string'  
}
}
};

My method to show singer's properties:

index: function(req, res, next){
    Singer.find().exec(function foundSinger(err, singerObj){
        if(err) return next(err);   
            res.view({
                singers: singerObj,
        });     
    });
},

My database is MongoDB, I am using sails beta 0.10 rc8. Thank you for helping.

Upvotes: 1

Views: 513

Answers (2)

Meeker
Meeker

Reputation: 5979

There are a lot of other variables here, but if you association is a one to one then your singer_country attribute needs to be something like

singer_country: {model: 'country'}

https://github.com/balderdashy/waterline-docs/blob/master/associations.md

Upvotes: 0

zieglar
zieglar

Reputation: 830

singer_country:{
    model: 'Country'
}

Singer.find().populate('singer_country').exec(function foundSinger(err, singerObj){
    if(err) return next(err);   
        res.view({
            singers: singerObj,
    });     
});

Upvotes: 1

Related Questions