Raggaer
Raggaer

Reputation: 3318

Sails.js model association

Currently my two models look like this

module.exports = {
    tableName: 'accounts',
    attributes: {
        id: {
            type: 'integer',
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: 'string',
            required: true
        },
        password: {
            type: 'string',
            required: true
        },
        email: {
            type: 'string',
            required: true
        },
        gang_name: {
            type: 'string',
            required: true
        },
        family_id: {
            type: 'string',
            required: true
        },
        world: {
            type: 'string',
            required: true
        },
        messages: {
            collection: 'Messages',
            via: 'for'
        }
    }
}

And my Messages model

module.exports = {
    tableName: 'messages',
    attributes: {
        id: {
            type: 'integer',
            primaryKey: true,
            autoIncrement: true
        },
        title: {
            type: 'string',
            required: true
        },
        text: {
            type: 'string',
            required: true
        },
        for: {
            model: 'Accounts',
            required: true
        },
        by: {
            type: 'integer',
            required: true
        }
    }
};

I want to associate the for field of a message with an account so if 'for' field is = 11 load account with id 11... Currently im trying this way

Accounts.find({ id: req.session.accountid }).populate('Messages').exec(function(err, data) {
            console.log(data, err);
        });

But Im getting an error

Attempting to populate an attribute that doesnt exist

Upvotes: 1

Views: 52

Answers (1)

Yann Bertrand
Yann Bertrand

Reputation: 3114

You've got to use the populate method with the attribute name ('messages'), not the model name ('Messages').

Upvotes: 2

Related Questions