veryphatic
veryphatic

Reputation: 5

SailsJS One to Many associations

Hi I'm building a Sails app with a couple of models in a one to many configuration. I've been able to create new instances of the models via the relationship, but it seems to be only working one way.

For reference (one) project can have (many) users.

/** Projects.js **/
name: {
    type: string
},

managers: {
    collection: 'Users',
    via: 'projects'
}

/** User.js **/
username: { 
    type: 'string'
},

projects { {
    model: 'Projects'
}

Using the following create method, results in the User have a reference to the Project, but no reference to the user is available to the Project. The managers reference is an array of user ids.

Project.create({ name: req.param('name'), managers: req.param('managers') }).exec(function newProject(err, results) {
    if (err) return res.json({ error: err });
    return res.json({ results: results });
});

And to retrieve the projects with their respective managers:

Project.findOne({ id: req.param('id') }).populate('managers').exec(function project(err, results) {
    if (err) return res.json({ error: err });
    return res.json({ results: results });
});

Upvotes: 0

Views: 641

Answers (1)

Melvin
Melvin

Reputation: 6008

Shouldn't

managers: {
    collection: 'Users',
    via: 'projects'
}

be like this:

managers: {
    collection: 'User',
    via: 'projects'
}

?...

You refer the collection to the Model filename. Refer to this documentation

Upvotes: 2

Related Questions