Search code examples
ormsails.jsone-to-manywaterlinesails-mongo

How can i get the full related model in view in sails.js?


I've created a sails.js application.

I'm trying to get full related model Creator in view but I get only id...

How can I do this?

I'm doing this:

Model Author.js

    module.exports = {

        attributes: {
            name: {
                type: 'string',
                required: true
            },
            description: {
                type: 'string'
            },
            history: {
                type: 'string'
            },

            creator: {
                model: 'User'
            }
        }
    };

model User.js

    module.exports = {


    attributes: {
        name: {
            type: 'string',
            required: true
        },
        email: {
            type: 'string',
            email: true,
            required: true,
            unique: true
        }
        authors: {
            collection: 'Author',
            via: 'creator'
        },
...
    }
};

AuthorController:

show: function(req, res, next) {
        Author.findOne(req.param('id'), function foundAuthor(err, author) {
            console.log(author.creator);
            res.view({
                author: author,
            });
        });

    }

and in my view author/show.ejs

<div class="container">

    <h1><%= author.name %></h1>
    <h3><%= author.creator %></h3>
    <h3><%= author.creator.name %></h3>


</div>

author.creator.name is undefined and author.creator is id

How can I get full model user instead id in author view?


Solution

  • you need to tell sails to populate the creator

    show: function(req, res, next) {
            Author.findOne(req.param('id').populate('creator').exec(function foundAuthor(err, author) {
                console.log(author.creator);
                res.view({
                    author: author,
                });
            });
        }