Reputation: 14440
I'm using recently released sails v0.10.2 and I can't get a many-to-many model association to work. Here's what I'm trying to build:
// models/Group.js
module.exports = {
identity: 'Group',
attributes: {
...
admins: {
collection: 'User',
via: 'groups',
dominant: true
},
...
// models/User.js
module.exports = {
identity: 'User',
attributes: {
...
groups: {
collection: 'Group',
via: 'admins'
},
...
This, to my knowledge, should set up a Many-to-Many association between these models. Both of them are stored on sails-memory for development.
// function is called when a group-creation form is filled in the frontend.
create: function(req, res, cb) {
Group.create( req.params.all() ).exec( function(err, group) {
if (err) { console.log(err); return cb(err); }
else {
group.admins.add(req.user.id);
group.save(function(err){
if(err){console.log(err);}
else {
console.log('binding user to group:');
console.log(req.user);
console.log(group);
}
});
res.json(group);
}
});
},
The output looks like this:
binding user to group
{ username: me
.. some other things ..
createdAt: Sat Aug 09 2014 10:13:15 GMT-0700 (PDT),
updatedAt: Sat Aug 09 2014 10:13:24 GMT-0700 (PDT),
id: 1 }
{ name: 'this is my group',
description: 'this is mah desccription',
tags: [ 'tag' ],
createdAt: Sat Aug 09 2014 10:13:43 GMT-0700 (PDT),
updatedAt: Sat Aug 09 2014 10:13:43 GMT-0700 (PDT),
id: 1 }
Which to me means that the groups field of the user model is not being modified, because not only isn't it present, but the updatedAt field doesn't register a change. There exist a couple possible reasons this is failing that I can think of:
Sails memory doesn't support model associations (even though I'm running v0.10.2)
Something very asynchronous and strange is happening.
Something involving the .populate() function.
Something else entirely.
Upvotes: 1
Views: 839
Reputation: 14440
So it turns out that I understand nothing about databases and joins. My assumption was essentially this:
My model has an admins attribute and the Groups.admins.add() function will find the User model and just kind of put a link to a user model in there, such that res.json(group) will return the group with an admins attribute populated with a User object on its own.
That turns out to not be the case, you need to manually .find() then .populate('fieldName') the model, which probably saves a bunch of overhead on the database end.
I initially had ~10 suspects (4 of which are sill above) and while knocking them out, I opened an issue frivolously on the sails-memory github, which a friendly banana helped me resolve.
https://github.com/balderdashy/sails-memory/issues/13#issuecomment-51862742
Upvotes: 1